[英]Is it possible to update the width of a chart in chart.js?
My use case is that I draw a chart with Chart.js, and when the user messes with certain options, I want to add or remove bars from the bar graph that I have drawn, and accordingly update the fixed width I had originally (programmatically) set on the chart. 我的用例是我使用Chart.js绘制图表,并且当用户使用某些选项时,我想从绘制的条形图中添加或删除条形,并相应地更新原来的固定宽度(以编程方式)设置在图表上。
Here's how I draw the chart: 这是我绘制图表的方式:
function drawChart(barData) {
oldData = barData;
var ctx = document.getElementById("estimateChart").getContext("2d");
ctx.canvas.width = getChartWidth(barData.length);
var chartData = {
labels: labels,
datasets: [
{
highlightFill: "#888888",
data: barData
}
]
};
window.barFill = new Chart(ctx).Bar(chartData, {
responsive: false
});
barFill.update();
}
Then when I update the chart, I do something like this 然后,当我更新图表时,我会做类似的事情
function updateChart(barData) {
angular.forEach(oldData, function () {
barFill.removeData();
});
oldData = barData;
angular.forEach(barData, function (newBar, i) {
barFill.addData([newBar], labels[i]);
});
barFill.chart.canvas.width = getWidth(barData);
barFill.update();
}
Everything works fine... except that the width does not change on the updateChart
call. 一切工作正常……除了在
updateChart
调用中宽度不变之外。 When I look at the width on the barFill
object, after the updateChart
call, my changes were not saved. 当我查看
barFill
对象的宽度时,在updateChart
调用之后,未保存我的更改。
I was unable to find anything about updating width in the Chart.js documentation, so I'm worried it may not be supported functionality out of the box. 我无法在Chart.js文档中找到有关更新宽度的任何信息,因此我担心开箱即用的功能可能不受支持。 Do I just have to just create a new Chart object and replace the canvas element on the DOM whenever I want to change the width?
每当我想更改宽度时,是否只需要创建一个新的Chart对象并替换DOM上的canvas元素? That would be unfortunate since I'd like to keep the nifty Chart.js animations that come with the built-in update function.
那样很不幸,因为我想保留内置的update函数附带的漂亮的Chart.js动画。
Instead of changing the barFill.chart.canvas.width. 而不是更改barFill.chart.canvas.width。 change barFill.
更改barFill。 scale .width.
比例尺
function updateChart(barData) {
angular.forEach(oldData, function () {
barFill.removeData();
});
oldData = barData;
angular.forEach(barData, function (newBar, i) {
barFill.addData([newBar], labels[i]);
});
barFill.scale.width = getWidth(barData);
barFill.resize().update();
}
It works even without the call to update()
by the way, but I just kept it because it is the right way as per the documentation. 即使没有调用
update()
,它也可以工作,但是我保留了它,因为根据文档,这是正确的方法。
I would recommend resizing the container instead of the canvas element btw. 我建议调整容器的大小,而不是canvas元素btw。
Fiddle - http://jsfiddle.net/ja8cxybf/ 小提琴-http: //jsfiddle.net/ja8cxybf/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.