canvas没有显示正确的宽度和高度chart.js

时间:2016-09-04 19:59:48

标签: chart.js

我使用画布宽度和高度如下

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

但是,当渲染页面时,画布会以某种方式变为

<canvas height="1643" id="myChart" width="1643" style="display: block; width: 1643px; height: 1643px;"></canvas>

我找到了similar problem,这样的解决方案也适用于我,

options: {
  responsive: false
}

但我不确定这是否是正确的解决方案只是为了关闭响应选项因为这是图表中的一个很酷的事情。

我的代码

<Html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.js" ></script>
</head>

<Body>
    <canvas id="myChart" height="400" width="400" ></canvas>
</Body>
<script>
      var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                datasets: [{
                    label: '# of Steps',
                    data: [12, 19, 3, 5, 2, 3],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',

                    ],
                    borderColor: [
                        'rgba(255,99,132,1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                },

                {
                label: "Goal Line",
                    type:'line',
                    data: [{x:0,y:10},{x:0,y:10},{x:0,y:10},{x:0,y:10},{x:0,y:10},{x:0,y:10}],
                    fill: false,
                    pointRadius:[0,0,0,0,0,0,0],
                    borderWidth: 5,
                    borderColor: "rgba(243, 52, 52,1)",
                    borderJoinStyle: 'miter',                                                

            }

                ]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        },         
                    }],
                         xAxes: [{
                        ticks: {
                            beginAtZero:true
                        },

                    }]
                },

            }
        });

</script>

</Html>

2 个答案:

答案 0 :(得分:4)

如果您想避免图表太大或太小,可以使用css max-width和min-width:

<canvas id="myChart" height="400" width="400" style="min-width: 200px; max-width: 600px"></canvas>

答案 1 :(得分:1)

注意:您不需要通过css设置宽度。您可以将元素放在网格列中。图表是响应式的,因此他们会将宽度调整为父级的大小。

&#13;
&#13;
<div class="col-md-5">
    <canvas id="myChart" ></canvas>
</div>
&#13;
&#13;
&#13;