Charts.js将画布的宽度/高度设置为0,什么也不显示 [英] Charts.js sets canvas width/height to 0 and displays nothing
问题描述
我正在尝试使用Charts.js制作它们在示例中动态显示的默认折线图,并将其放置在用户单击时弹出的div中。我的代码是这样的:
I am trying to use Charts.js to make the default line plot that they show in their example dynamically and put it in a div that I pop up on a user click. My code is like this:
this.chartCanvas = document.createElement('canvas');
this.div.appendChild(this.chartCanvas);
this.chartCanvas.style.height = '480px';
this.chartCanvas.style.width = '900px';
this.chartCanvas.width = 900;
this.chartCanvas.height = 480;
this.ctx = this.chartCanvas.getContext('2d');
this.chart = new Chart(this.ctx).Line(data);
当我调用新图表时,我的画布高度和宽度设置为0可以在检查器中看到。当我注释掉此呼叫时,我的画布具有适当的宽度/高度,并按预期显示。如果我在检查器中手动更改画布的高度/宽度,我的图表仍不会显示。
When I make the call to "new Chart" my canvas height and width are set to 0 as I can see in the inspector. When I comment out this call my canvas has the proper width/height and displays as one would expect. If I manually change the canvas height/width in the inspector my chart still doesn't display.
我的数据对象就是我直接从其剪切并粘贴的对象此处的折线图示例: http://www.chartjs.org/docs/# line-chart-example-usage
My "data" object is just what I cut and paste directly from their line chart example here: http://www.chartjs.org/docs/#line-chart-example-usage
任何人都可以对我可能会出错的地方提供一些见解,我是图书馆的新手。
Can anyone provide some insight on where I might be going wrong, I am completely new to the library.
推荐答案
问题似乎是在进行图表调用时画布及其所有父节点无法显示任何内容,因此如果您正在弹出窗口中使用图表,则需要显示弹出窗口,构造图表,然后隐藏弹出窗口。
It appears that the issue is that the canvas and all its parent nodes cannot have display none at the time the chart call is made so if you are using a chart in a popup you need to show the popup, construct the chart and then hide the popup.
如小提琴所示,如果您尝试构建一个弹出窗口,在隐藏的div中显示图表,然后在超时时显示它不起作用。
As this Fiddle shows, if you try and construct a chart in a hidden div and then show it on a timeout it does not work.
如果您改为显示div,则制作图表然后隐藏div,它确实可以工作。
If you instead show the div, make the chart and then hide the div, it does work.
http://jsfiddle.net/bjudheoq/4/
//This will break it
//this.div.style.display = 'none';
this.chart = new Chart(this.ctx).Line(data);
this.div.style.display = 'none';
上面的小提琴有效,但是如果您取消注释第40行,则不会。
The above fiddle works, but if you uncomment line 40 it does not.
这篇关于Charts.js将画布的宽度/高度设置为0,什么也不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!