简体   繁体   English

Chart.js 中的宽度和高度

[英]Width and Height in Chart.js

I was using Chart.js and found that it recognizes the following two style s differently— <canvas style=""> works well, while <style>canvas{} distorts the charts.我在使用 Chart.js 时发现它对以下两种style的识别style不同—— <canvas style="">效果很好,而<style>canvas{}扭曲了图表。 Here're two examples.这里有两个例子。

<!doctype html>
<html>

<canvas id=Figure1 style="width:640px;height:480px"></canvas>

<script src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js></script>
<script>
new Chart(document.getElementById("Figure1"),{type:"scatter",data:{datasets:[{data:[{x:1,y:1},{x:2,y:2},{x:3,y:3}]}]},options:{responsive:false}});
</script>
</html>

This code doesn't twist the image, so I wanted to apply the settings globally with the code below.此代码不会扭曲图像,因此我想使用以下代码全局应用设置。

<!doctype html>
<html>

<style>canvas{width:640px;height:480px}</style>

<canvas id=Figure1></canvas>
<script src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js></script>
<script>
new Chart(document.getElementById("Figure1"),{type:"scatter",data:{datasets:[{data:[{x:1,y:1},{x:2,y:2},{x:3,y:3}]}]},options:{responsive:false}});
</script>
</html>

I just relocated width:640px;height:480px in this code, but it stretches the image weirdly.我只是在这段代码中重新定位了width:640px;height:480px ,但它奇怪地拉伸了图像。 Must I always use <canvas style=""> to resize the Chart.js images?我必须总是使用<canvas style="">来调整 Chart.js 图像的大小吗?

There are many ways to specify the canvas' height and width.有很多方法可以指定画布的高度和宽度。 But what's the difference between the two methods you tried?但是您尝试的两种方法有什么区别? Well, the full explanation can be found here Canvas is stretched when using CSS but normal with "width" / "height" properties好吧,完整的解释可以在这里找到Canvas 在使用 CSS 时被拉伸,但使用“宽度”/“高度”属性是正常的

PS You can make the chart responsive by having responsive: true and putting your canvas inside a div. PS 您可以通过响应式使图表具有响应性:true 并将您的画布放在 div 中。 That way, the canvas will always take its container's dimensions.这样,画布将始终采用其容器的尺寸。

 let line_chart = document.getElementById("line-chart"); new Chart(line_chart, { type: 'scatter', data: { datasets: [{ label: 'Sample Data', data: [{ x: 1, y: 1 }, { x: 2, y: 2 }, { x: 3, y: 3 }] }], }, options: { responsive:true, } });
 /* If you change the wrapper's height and width, the chart will follow the wrapper's dimensions */ .wrapper{ height: 200px; width: 300px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.js"></script> <div class="wrapper"> <canvas id="line-chart"></canvas> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM