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 g
Make a div element and place the chart canvas inside of it, name it as canvas-holder. See below:
<div id="canvas-holder">
<canvas id="myChart"></canvas>
</div>
Using CSS, specify the height and width of the canvas holder
#canvas-holder {
background-color: #FFFFFF;
position: absolute;
width: 400px;
height: 400px;
}
The real issue is that the canvas will re-scale responsively to its parent. I wanted to keep the responsiveness. So something like this will solve the issue:
<div style="width:50%">
<canvas id="myChart"></canvas>
</div>
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
}
});
}
Below code from Chart.js documentation worked for me. "https://www.chartjs.org/docs/latest/general/responsive.html"
var ctx = document.getElementById('myChart').getContext('2d');
ctx.canvas.parentNode.style.width = "500px";
ctx.canvas.parentNode.style.height = "500px";
var myChart = new Chart(ctx, .....
A little late to the party, but I struggled with this problem a lot, particularly on a page with multiple charts.
This little tidbit solved it all - my charts all now fit nicely, and resize exactly with the divs they are in.
Add this to your page styles (The 8px is personal preference. Change if needed):
<style type="text/css">
#canvas-holder {
background-color: #FFFFFF;
position: absolute;
top: 8px;
left: 8px;
right: 8px;
bottom: 8px;
}
</style>
For the appropriate Divs:
<div id="canvas-holder">
<canvas id="chart-area"></canvas>
</div>