javascript - Chart.js 不遵守我的容器尺寸

标签 javascript jquery html css chart.js

我正在尝试使用 Chart.js 库创建折线图。我有一个尺寸为 600px 宽 x 250px 高的 div,根据我的阅读,该库旨在使用这些父尺寸创建折线图。

下面显示了我的 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)

最佳答案

您需要将选项 maintainAspectRatio 设置为 false

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

fiddle - https://jsfiddle.net/3cxeyLc8/

关于javascript - Chart.js 不遵守我的容器尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32459948/

相关文章:

javascript - 保存前添加确认提示 x-editable

javascript - 使用 JQuery 样式化嵌套滚动条

javascript - jQuery - 从 html 构建对象

ios - 如何更改 IOS 时间输入的步骤?

javascript - JS Fetch API 不适用于具有授权属性的 ASP.NET Core 2 Controller

javascript - 我希望更新未读消息的数量,并在用户收到新消息时播放通知声音。我使用 PHP、MySql、Javascript

php - Javascript 警报不在 php 联系表单中显示变音符号

c# - 在这种情况下使用什么会更好? C# 还是 PHP?

javascript - ajax查询中从div获取数据

javascript - 问题: The whole page loading instead just the div with .加载()