Chart.js不尊重我的容器尺寸

时间:2015-09-08 14:05:44

标签: javascript jquery html css chart.js

我尝试使用Chart.js库创建折线图。我有div尺寸为600px宽,250px高度的尺寸,而我从中读到的图书库是用这些父尺寸创建折线图。

以下显示了我的HTML元素:

<div style="width:600px;height:250px">
    <canvas id="myChart"></canvas>
</div>

这是我使用的代码:

$(document).ready(function(){
     var data = {
                    labels: ["January", "February", "March", "April", "May", "June", "July"],
                    datasets: [
                        {
                            label: "My First dataset",
                            fillColor: "rgba(220,220,220,0.2)",
                            strokeColor: "rgba(220,220,220,1)",
                            pointColor: "rgba(220,220,220,1)",
                            pointStrokeColor: "#fff",
                            pointHighlightFill: "#fff",
                            pointHighlightStroke: "rgba(220,220,220,1)",
                            data: [65, 59, 80, 81, 56, 55, 40]
                        },
                        {
                            label: "My Second dataset",
                            fillColor: "rgba(151,187,205,0.2)",
                            strokeColor: "rgba(151,187,205,1)",
                            pointColor: "rgba(151,187,205,1)",
                            pointStrokeColor: "#fff",
                            pointHighlightFill: "#fff",
                            pointHighlightStroke: "rgba(151,187,205,1)",
                            data: [28, 48, 40, 19, 86, 27, 90]
                        }
                    ]
                };
                var ctx = $("#myChart").get(0).getContext("2d");
                new Chart(ctx).Line(data, {
                    responsive:true
                });
});

这显示了我在jsfiddle中遇到的问题:https://jsfiddle.net/Lr88htnp/(请注意,渲染图表的尺寸为600x300)

3 个答案:

答案 0 :(得分:26)

您需要将选项maintainAspectRatio设置为false

....
new Chart(ctx).Line(data, {
    responsive:true,
    maintainAspectRatio: false
});

小提琴 - https://jsfiddle.net/3cxeyLc8/

答案 1 :(得分:7)

将以下CSS添加到#myChart:

 <canvas id="myChart" style="width:100%;height:100%;"></canvas>

答案 2 :(得分:0)

设置宽度和高度 100% 对我有用

<LineChart :chart-data="chartData1" :options="options" style="width: 100%; height: 100%" />