I'm trying to make a graph with Charts.js (current one is just a really simple example I'm trying to get working, somewhat taken from the Chart.js documentation) and the graph isn't scaling to the size of the canvas I'm giving it. Here is all the relevant code.
To import it:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.min.js"></script>
Then, I connect it to a javascript file as follows:
<script type="text/javascript" src="js/stats_tab.js"></script>
I have my canvas set up:
<div id="graph_2015" class ="stats_box"> <h4>Graph 2015</h4> Text <canvas id="myChart" width="200" height="200"></canvas> </div>
And then finally in stats_tab.js, I have the following code:
window.onload=function(){ var ctx = document.getElementById("myChart").getContext("2d"); var myChart = new Chart(ctx, { type: 'line', data: { labels: [1,2,3,4,5,6,7,8,9,10], datasets: [ { label: "My First dataset", data: [1,2,3,2,1,2,3,4,5,4] } ] }, options: { } }); }
The graph displays nicely, but it refuses to scale to the size of the canvas I gave it. There is also no css relevant to any of the divs involved. The inspect feature on chrome lets me know that the final graph is 676 by 676 instead of the 200 by 200 I specified. Not really sure what's going on.
Thanks!
You can resize the chart using the resize function that is provided by KoolChart's JavaScript charting library. Set the width and height of the <DIV> element where the chart is created before the resize function is called.
Canvas aspect ratio (i.e. width / height , a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style. The default value varies by chart type; Radial charts (doughnut, pie, polarArea, radar) default to 1 and others default to 2 .
Let's get started using Chart. js! First, we need to have a canvas in our page. It's recommended to give the chart its own container for responsiveness.
To make chart responsive just set responsive key to true inside lineChartOptions. Also, remember to remove :width and :height properties from the element and make the wrapper element responsive via css/scss.
The width and height property that you set for the canvas only work if the Chartjs' responsive mode is false (which is true by default). Change your stats_tab.js to this and it will work.
window.onload=function(){ var ctx = document.getElementById("myChart").getContext("2d"); var myChart = new Chart(ctx, { type: 'line', data: { labels: [1,2,3,4,5,6,7,8,9,10], datasets: [ { label: "My First dataset", data: [1,2,3,2,1,2,3,4,5,4] } ] }, options: { responsive: false } }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With