[英]ChartJS + jQuery = Chart not showing
I'm trying to create a Dounught chart with ChartJS: 我正在尝试使用ChartJS创建Dounught图表:
$(function() {
//...
drawChart();
});
function drawChart() {
var ctx = document.getElementById("currenciesTag").getContext("2d");
new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Label1', 'Label2'],
datasets: [{
backgroundColor: ['#000000', '#000000'],
borderColor: 'rgb(255, 99, 132)',
data: [1, 2],
}]
},
options: {}
});
}
Actually, I need to draw my chart in $(function() {} because dataset comes from elements used by jQuery. But, my chart is not showing. Its canvas is resized so something happens. 实际上,我需要在$(function(){}中绘制图表,因为数据集来自jQuery使用的元素。但是,图表未显示,其画布已调整大小,因此发生了某些事情。
If I put the content of drawChart() outside any function, it works and my charts is showing. 如果我将drawChart()的内容放在任何函数之外,则它可以工作并且我的图表正在显示。 But I need to draw it from inside $(function() {}
但是我需要从$(function(){}内部绘制它
You're probably not able to get a hold of ctx
. 您可能无法获得
ctx
。
Inspect with the console like this: 像这样检查控制台:
var ctx = document.getElementById("currenciesTag").getContext("2d");
console.log(ctx);
Check your html and make sure you have, for example: 检查您的html并确保您拥有,例如:
<body>
<canvas id="currenciesTag" width="600" height="400"></canvas>
</body>
You can see your code working here: 您可以在这里看到您的代码:
https://jsfiddle.net/zwjj20L5/ https://jsfiddle.net/zwjj20L5/
I had same problem and it takes 4.5 hours to solve it god damn nevermind if you have 我有同样的问题,要花4.5个小时才能解决,如果你有的话,该死的没关系
window.onload = function() { }
outside of your 在你外面
var ctx = document.getElementById('canvas').getContext('2d');
code just delete it after that you can use it in any function like $(function() { }); 代码只是删除它,然后您就可以在$(function(){})之类的任何函数中使用它了; or button click.
或按钮单击。 Have a nice day :)
祝你今天愉快 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.