我正在尝试使用Chartjs和Requirejs渲染图表,但无法呈现或提供错误消息。我知道我可能很累,并且遗漏了一些明显的东西,但我似乎无法弄明白。
我的HTML中用于保存图表画布的行如下:
<canvas id="canvas" height="450" width="600"></canvas>
我的Requirejs文件如下。在这里,我怀疑这个问题:
require.config({
paths: {
jquery: "jquery-2.1.1.min",
bootstrap: "bootstrap.min",
chartjs: "Chart.min"
},
shim: {
bootstrap: {
deps: ['jquery'],
exports: 'Bootstrap'
},
}
});
requirejs(['bootstrap'], function (Bootstrap) {
return {};
});
require(['chartjs'], function (Chart) {
// Use Chart.js as normal here.
var randomScalingFactor = function () { return Math.round(Math.random() * 100) };
var lineChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}
]
}
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
// Chart.noConflict restores the Chart global variable to it's previous owner
// The function returns what was previously Chart, allowing you to reassign.
var chartjs = Chart.noConflict();
});
答案 0 :(得分:1)
您所描述的内容与您提供给window.onload
的事件处理程序完全一致。
当RequireJS开始执行require(['chartjs']
调用中的代码时,load
事件很可能已经发生。你可以做的是使用jQuery的ready
或RequireJS&#39; domReady
顺便说一句,这段代码很奇怪:
requirejs(['bootstrap'], function (Bootstrap) {
return {};
});
如果您只是加载bootstrap,可以将其减少到requirejs(['bootstrap'])
。但请注意,所有加载都是异步的,因此唯一要做的就是告诉RequireJS加载Bootstrap,这将在未来的某个不确定点发生。