Reputation: 19
Noob trying to learn how to use chart.js and I keep getting "Uncaught ReferenceError: myChart is not defined" when trying to update a chart.
My ultimate goal is to be able to put the chart in a lightbox, including thumbnail which seems to be working ok. Just cant update the chart.
Heres my barChart.js code. This code is in a seperate .js file.. .
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);
}
}
}
});
}
Below is my update code:
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();
Im not sure why the instantiated chart's name is wrong?
html code :
<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>
Thanks in advance
Upvotes: 1
Views: 1005
Reputation: 61275
the chart needs to be declared outside of the function --> drawBarChart
in order to be accessed from another function --> update
like this...
// 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, {
...
Upvotes: 1