Charts.js graph not scaling to canvas size

antonin_scalia picture antonin_scalia · Jul 21, 2016 · Viewed 75.3k times · Source

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!

Answer

Duc Vu Nguyen picture Duc Vu Nguyen · Apr 7, 2017

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