设置宽度和高度


84

我正在尝试docs中给出的Chart.js示例代码。

在canvas元素上以400px / 400px内联指定宽度和高度。

但是,在渲染图表时,它会被放大到整个页面宽度,并切断最右端。

看例子

我应该如何/在哪里控制图表的宽度/高度?

This is some bogus text because SO prohibits linking to Codepen otherwise.

Answers:


89

您可以覆盖画布样式的宽度!重要...

canvas{

  width:1000px !important;
  height:600px !important;

}

responsive:true,在选项下指定属性。

options: {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero:true
            }
        }]
    }
}

在添加的选项下更新: maintainAspectRatio: false,

链接:http//codepen.io/theConstructor/pen/KMpqvo


11
谢谢,您maintainAspectRatio: false使图表可见。但是仍然切断右侧。他们自己的基本示例代码已经碰到了这类问题,这让我想知道,是否Chart.js是一个不错的选择。(右侧仍被切除...)
陌生人研究员

这就解决了图形大小的问题,图形没有缩放到适合它的大小。有没有办法在Chart.js中设置图形大小?
Firix

7
原来,您需要关闭响应才能使图服从给定的大小。
感到遗憾的

2
谢谢。你maintainAspectRatio真的对我有帮助。
Arsman Ahmad

即使有效,使用“!important”也不是解决此问题的正确方法。@Nicolas解决方案“将画布包装成div”下面的方法是一种更好的方法,因为我们可以控制画布的大小调整。
Abhishek Boorugu

53

您还可以将图表简单地用容器围起来(根据官方文档http://www.chartjs.org/docs/latest/general/sensitive.html#important-note

<div class="chart-container">
    <canvas id="myCanvas"></canvas>
</div>

的CSS

.chart-container {
    width: 1000px;
    height:600px
}

和选项

responsive:true
maintainAspectRatio: false

1
这有效。这里的关键是使用外部div并在其上设置宽度和高度,而不是canvas元素。
John Doherty

为了使其正常工作,图表容器应相对放置。
Sanju

对我的作品,但只!important在角项目
АртурГудиев

21

就我而言,responsive: false在选项下传递可以解决问题。我不确定为什么每个人都告诉你做相反的事情,特别是因为默认是true。


同样在这里。设置responsive: true完全歪曲了图表的外观。
保罗

对我的作品,但只有用!important我的角项目
АртурГудиев

2

也为我工作

responsive:true
maintainAspectRatio: false


<div class="row">
        <div class="col-xs-12">
            <canvas id="mycanvas" width="500" height="300"></canvas>
        </div>
    </div>

谢谢


2

我不敢相信没有人谈论过使用相对父元素。

码:

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
  <canvas id="chart"></canvas>
</div>

资料来源:官方文件


0

上面没有提到,但是在canvas元素上使用max-widthmax-height也可以。


0

下面为我​​工作-但不要忘记将其放在“选项”参数中。

var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
    maintainAspectRatio: false,
    responsive:true,
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}
});

0

这对我来说有帮助:

options: {
    responsive: true,
    scales: {
        yAxes: [{
            display: true,
            ticks: {
                min:0,
                max:100
            }
        }]
    }
}

-3

使用它,可以正常工作。

<canvas id="totalschart" style="height:400px;width: content-box;"></canvas>

而下options

responsive:true,
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.