Noob尝试学习如何使用chart.js,并且在尝试更新图表时不断收到“ Uncaught ReferenceError:未定义myChart”。
我的最终目标是能够将图表放入灯箱中,其中包括缩略图似乎可以正常工作。只是无法更新图表。
这里是我的barChart.js代码。这段代码在单独的.js文件中。
function drawBarChart() {
console.log("drawing bar . . .");
var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext('2d');
var myChart = new Chart(ctx, {
data: {
labels: mylabel,
datasets: [{
label: '# of Votes',
data: data
,
backgroundColor: [
'black',
'green',
'yellow',
'orange',
'red',
'blue',
'pink'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: { responsive: true,
annotations: {
tooltip: {
tooltipFontSize:18},
textStyle: {
fontName: 'TimesNewRoman',
fontSize: 12,
bold: false}
},
animation: {
onComplete: //put chart into lightbox
function getPicToLightbox() {
var urlCode
=document.getElementById("myCanvas").toDataURL();
document.getElementById("url").innerHTML = urlCode;
var imgTag =
document.getElementById("imageSource");
imgTag.src= urlCode;
imgTag.href = urlCode;
var getLightBox =
document.getElementById("lightbox1");
getLightBox.href = urlCode;
console.log("imgTag = " + imgTag);
}
}
}
});
}
以下是我的更新代码:
function update() {
addData(myChart,mylabel ,data);
addData(myRadarChart,mylabel ,data);
var urlCode
=document.getElementById("myCanvas").toDataURL();
document.getElementById("url").innerHTML = urlCode;
var imgTag =
document.getElementById("imageSource");
imgTag.src= urlCode;
imgTag.href = urlCode;
var getLightBox =
document.getElementById("lightbox1");
getLightBox.href = urlCode;
console.log("imgTag = " + imgTag);
};
function addData(chart, label, data) {
chart.data.labels = label;
chart.data.datasets.forEach((dataset) => {
dataset.data = data;
});
chart.update();
我不确定为什么实例化图表的名称错误吗?
html代码:
<div id ="chart_div">
<canvas id="myCanvas" ></canvas> <!--
style="display:none" put on other page-->
<canvas id="myChart2"></canvas>
<div id ="gauge"></div>
<div id="piechart"></div> <!--//style="width:
900px; height: 500px;"-->
</div>
<a href="" id = "lightbox1" data-
lightbox="barChart" >
<img id = "imageSource" src = ""/>
</a>
预先感谢
答案 0 :(得分:0)
图表需要在函数之外声明-> drawBarChart
以便从另一个功能-> update
像这样...
// add declaration here
var myChart;
function drawBarChart() {
console.log("drawing bar . . .");
var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext('2d');
// remove var here
myChart = new Chart(ctx, {
...