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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38512001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:33:14  来源:igfitidea点击:

Charts.js graph not scaling to canvas size

javascriptcanvaschartschart.js

提问by antonin_scalia

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.

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

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:

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

<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:

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

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.

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

Thanks!

谢谢!

回答by Duc Vu Nguyen

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.

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

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

回答by Opsse

The important point is: widthand heightproperties are not the size in px but the ratio.

重要的一点是:widthheight属性不是以px为单位的大小,而是比例。

<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.

在这个例子中,它是一个 1:1 的比例。因此,如果您的 html contenair 宽度为 676 px,那么您的图表将为 676*675px
这可以解释一些常见错误。

You can disable this feature by setting maintainAspectRatioto false.

您可以通过设置maintainAspectRatio为 false来禁用此功能。

回答by Kurt Van den Branden

In your options, set the maintainAspectRatioto false, and responsiveto 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.

在你的选择中,设置maintainAspectRatiofalse,并responsivetrue。这将首先尝试缩放图表以匹配画布的尺寸。如果画布不适合屏幕,即在手机上,您的图表将重新缩放以适合页面。

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

回答by Darryn Frost

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.

这个小花絮解决了这一切 - 我的图表现在都很好地适合,并且与它们所在的 div 完全一致。

Add this to your page styles (The 8px is personal preference. Change if needed):

将此添加到您的页面样式(8px 是个人偏好。如果需要,请更改):

<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:

<div id="canvas-holder">
    <canvas id="chart-area"></canvas>
</div>

回答by Ryan Forte

I had this exact same problem where my graph would not resize properly. To get around this issue I did two things.

我遇到了完全相同的问题,我的图表无法正确调整大小。为了解决这个问题,我做了两件事。

  1. Set the canvas tag style to a width and height of 100%. This will make sure that it always fits 100% of its containers width and height.
  2. For the options value set responsive: true & maintainAspectRatio: false. This will make sure that the graph responds to updates in size while ignoring the aspect ratio.
  1. 将画布标签样式设置为 100% 的宽度和高度。这将确保它始终适合其容器宽度和高度的 100%。
  2. 对于选项值设置responsive: true 和maintainAspectRatio: false。这将确保图形在忽略纵横比的同时响应大小的更新。

below is the code I used:

下面是我使用的代码:

css
#myGraph {
width: 100%;
height: 100%;
}

html
<canvas id="myGraph" />

When you initialise the chart with the ctx set the options as below:

当您使用 ctx 初始化图表时,请设置如下选项:

   

 options: {
            responsive: true,
            maintainAspectRatio: false
            }

now when you resize your screen the graph should resize accordingly. Note: The graph will fill the size of its container now so what ever you put your canvas into it will fill the size of that container.

现在,当您调整屏幕大小时,图形应相应调整大小。注意:图形现在将填充其容器的大小,因此您将画布放入其中的任何内容都将填充该容器的大小。

回答by Timothy Chen

Thisshould work. Basically, just add the width and height properties to your javascript:

应该有效。基本上,只需将宽度和高度属性添加到您的 javascript 中:

var ctx = document.getElementById("myChart").getContext("2d");
ctx.canvas.width = 200;
ctx.canvas.height = 200;
var myChart = new Chart(ctx,.........

Reference: Chart.js canvas resize

参考:Chart.js 画布调整大小

回答by Mohd Abdul Mujib

If your <canvas>element doesn't have a width& a height"attribute" (not the css attribute). Try setting each of them them to 1 (Since its just a ratio)

如果您的<canvas>元素没有width& 一个height属性”(不是 css 属性)。尝试将它们每个设置为 1(因为它只是一个比率

<canvas id="activeUsersPieChart" width="1" height="1"></canvas>

回答by Joshua Schlichting

The following worked for me, and I was able to keep the responsiveness of the chart!

以下对我有用,我能够保持图表的响应能力!

  var ctxx = document.getElementById("myChart");
  ctxx.height = 80;

回答by Arun

Below code from Chart.js documentation worked for me. "https://www.chartjs.org/docs/latest/general/responsive.html"

下面来自 Chart.js 文档的代码对我有用。“ 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, .....

回答by Sharpiro

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>