Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Charts.js sets canvas width/height to 0 and displays nothing

Tags:

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);

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.

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.

like image 816
asutherland Avatar asked Sep 18 '15 21:09

asutherland


2 Answers

In my case the canvas needed to be wrapped inside an element with the CSS display: block;

like image 150
Stefan Rein Avatar answered Sep 22 '22 07:09

Stefan Rein


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.

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.

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';

The above fiddle works, but if you uncomment line 40 it does not.

like image 42
asutherland Avatar answered Sep 18 '22 07:09

asutherland