我试图做一个按钮,清除/破坏画布上的图表,这样我就可以在同一个画布上做一个新的,但我一直得到我的函数被声明,但它的值从来没有读。我该如何解决这个问题?我将分享我的很多代码下,这样它更容易帮助我,但代码混乱。
于飞:
<!--Canvas for chart-->
<canvas id="chart"></canvas>
<!-- https://www.chartjs.org/docs/latest/ -->
<script id="graph1" type="text/JavaScript" src="js/Main.js"></script>
<button type="button" id="generate" onclick="generateGraph()">Generate</button>
<button type="button" id="clear" onclick="clearCanvas()">Clear</button>
JavaScript语言:
//Url for JSON-file
var url = "";
//The labels for the chart
var graphLabels = [];
var generateButton = document.getElementById("generate");
//When a checkbox is checked (function)
function generateGraph(url) {
var arrayTheta = [];
var arrayRange = [];
var mcsArray = [];
var channelArray = [];
//Getting the data from json-file (function) {NOTE: gotta figure out a way to get data from multible JSON-files}
async function getData(arrayRange, arrayTheta, url, graphLabels, mcsArray, channelArray) {
//Gets data from the JSON-file, were the url is the box that is checked
const response = await fetch(url);
const productData = await response.json();
for (let index = 0; index < productData.length; index++) {
arrayTheta.push(productData[index].theta);
arrayRange.push(productData[index].Range);
}
//The graph, copied from Chart.js, but changed for our prefrence
const ctx = document.getElementById('chart').getContext('2d');
const myChart = new Chart(ctx,{
type: 'line',
data: {
labels: arrayTheta,
datasets: [{
label: graphLabels,
data: arrayRange,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
pointRadius: 0,
tension: 0.4
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
,x: {
display: true,
type: 'linear'
}
}
}
});
}
getData(arrayRange, arrayTheta, url, graphLabels, mcsArray, channelArray)
//Trying to make a clear button, but does not work (Remove this comment when it works)
var clearButton = document.getElementById("clear")
function clearCanvas() {
console.log("DETROYINGG")
myChart.destroy()
}
}
我希望这个代码足以帮助我,但如果你需要更多,我也可以发送。
1条答案
按热度按时间flvtvl501#
您的
const myChart
声明在generateGraph
函数内部,只有generateGraph
内部的代码可以访问const myChart
您可以使用
window.myChart
而不是const myChart
,这样变量就可以全局使用,并且您的clearCanvas()
函数也可以使用window.myChart.destroy()
来访问它