Charts.js 图表未缩放到画布大小

2022-01-22 00:00:00 canvas charts javascript chart.js

我正在尝试使用 Charts.js 制作图表(当前的只是我正在尝试开始工作的一个非常简单的示例,在某种程度上取自 Chart.js 文档)并且该图表没有缩放到我给它的画布的大小.这是所有相关代码.

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.

要导入它:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.min.js"></script>

然后,我将它连接到一个 javascript 文件,如下所示:

Then, I connect it to a javascript file as follows:

<script type="text/javascript" src="js/stats_tab.js"></script>

我的画布设置好了:

        <div id="graph_2015" class ="stats_box">
            <h4>Graph 2015</h4>
            Text
            <canvas id="myChart" width="200" height="200"></canvas>
        </div>

最后在 stats_tab.js 中,我有以下代码:

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

图表显示得很好,但它拒绝缩放到我给它的画布的大小.也没有与所涉及的任何 div 相关的 css.chrome 上的检查功能让我知道最终图形是 676 x 676 而不是我指定的 200 x 200.不太清楚发生了什么.

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.

谢谢!

推荐答案

您为画布设置的 width 和 height 属性仅在 Chartjs 的响应模式为 false(默认为 true)时才有效.将您的 stats_tab.js 更改为此,它将起作用.

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

相关文章