Charts.js graph not scaling to canvas size Charts.js graph not scaling to canvas size javascript javascript

Charts.js graph not scaling to canvas size


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


The important point is: width and height properties are not the size in px but the ratio.

<canvas id="myChart" width="400" height="400"></canvas>

In this example, it's a 1:1 ratio. So, if your html contenair is 676 px width then your chart will be 676*675px
That can explain some common mistakes.

You can disable this feature by setting maintainAspectRatio to false.


In your options, set the maintainAspectRatio to false, and responsive to true. This will initially try to scale your chart to match the dimensions of your canvas. If the canvas doesn't fit the screen, i.e. on mobiles, your chart will be re-scaled to fit on the page.

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: true,            maintainAspectRatio: false,        }    });}