我的图表未显示在浏览器屏幕上。我将 Chart.js 与 Meteor 结合使用,并尝试使用 onRendered 或 onCreated 来实现,但它对我不起作用。
这是我的代码
<div class="pie-canvas">
<canvas id="myChart" width="350" height="350"></canvas>
</div>
Js 文件 ->
Template.home.rendered = function() {
Deps.autorun(function() { drawChart(); });
};
function drawChart() {
var oldCount = 2;
var newCount = 4;
var data = [{
value: newCount,
color: "#e53935",
highlight: "#c62828",
label: "New"
}, {
value: oldCount,
color: "#3949ab",
highlight: "#1a237e",
label: "Regular"
}];
var pieOptions = {
animation: false,
}
if ($("#myChart").get(0)) {
var ctx = $("#myChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx);
new Chart(ctx).Pie(data, pieOptions);
}
}
home 是我的模板名称
最佳答案
当您控制台日志 '$("#myChart").get(0)' 时,这将返回您未定义的结果,因为在渲染时您的 get(0) 未初始化,为了防止这种情况,您必须添加一个回调,当您初始化了你的图表。因此,您的 get(0) 将首先初始化,然后您就可以创建聊天。
'$("#myChart").get(0)' 不是一个相对的东西,因此您的 View 不会重新初始化。
这是工作代码:
function drawChart() {
var oldCount = 2;
var newCount = 4;
var data = [{
value: newCount,
color: "#e53935",
highlight: "#c62828",
label: "New"
}, {
value: oldCount,
color: "#3949ab",
highlight: "#1a237e",
label: "Regular"
}];
var pieOptions = {
animation: false,
}
// Added a callback here.
setTimeout( function(){
if ($("#myChart").get(0)) {
var ctx = $("#myChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx);
console.log(myNewChart);
new Chart(ctx).Pie(data, pieOptions);
}
})
}
关于javascript - 在 meteor 中使用 Chart.js 我的图表未显示在浏览器屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38759683/