chart.js 加载全新数据
chart.js
的 API 允许编辑加载到其中的数据集,例如:
The API for chart.js
allows one to edit points of the datasets loaded into it, for example:
在 Chart 实例上调用 update() 将重新渲染图表任何更新的值,允许您编辑多个值现有点,然后在一个动画渲染循环中渲染它们.
.update( )
Calling update() on your Chart instance will re-render the chart with any updated values, allowing you to edit the value of multiple existing points, then render those in one animated render loop.
在您的 Chart 实例上调用 addData(valuesArray, label) 传递一个每个数据集的值数组,以及这些点的标签.
Calling addData(valuesArray, label) on your Chart instance passing an array of values for each dataset, along with a label for those points.
在您的 Chart 实例上调用 removeData() 将删除第一个图表上所有数据集的值.
Calling removeData() on your Chart instance will remove the first value for all datasets on the chart.
所有这些都很棒,但我不知道如何加载一个全新的数据集,消除旧的.文档似乎没有涵盖这一点.
All of these are great, but I cannot figure out how to load an entirely new dataset in, wiping out the old. The documentation does not seem to cover this.
推荐答案
我遇到了很大的问题
首先我尝试了 .clear()
然后我尝试了 .destroy()
并尝试将我的图表引用设置为 null
First I tried .clear()
then I tried .destroy()
and I tried setting my chart reference to null
最终解决了我的问题:删除 <canvas>
元素,然后将新的 <canvas>
重新附加到父容器
What finally fixed the issue for me: deleting the <canvas>
element and then reappending a new <canvas>
to the parent container
有一百万种方法可以做到这一点:
There's a million ways to do this:
var resetCanvas = function () {
$('#results-graph').remove(); // this is my <canvas> element
$('#graph-container').append('<canvas id="results-graph"><canvas>');
canvas = document.querySelector('#results-graph'); // why use jQuery?
ctx = canvas.getContext('2d');
ctx.canvas.width = $('#graph').width(); // resize to parent width
ctx.canvas.height = $('#graph').height(); // resize to parent height
var x = canvas.width/2;
var y = canvas.height/2;
ctx.font = '10pt Verdana';
ctx.textAlign = 'center';
ctx.fillText('This text is centered on the canvas', x, y);
};
相关文章