我正在使用Chart.js并发现它识别以下两个style
s不同 - <canvas style="">
运作良好,而<style>canvas{}
扭曲图表。这是两个例子。
<!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>
此代码不会扭曲图像,因此我想使用下面的代码全局应用设置。
<!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>
我刚刚在这段代码中重新定位了width:640px;height:480px
,但它却奇怪地延伸了图像。我必须始终使用<canvas style="">
来调整Chart.js图像的大小吗?
指定画布的高度和宽度有很多种方法。但是你试过的两种方法有什么区别?好吧,完整的解释可以在这里找到Canvas is stretched when using CSS but normal with "width" / "height" properties
P.S你可以通过响应:使真实并将你的画布放在div中来使图表响应。这样,画布将始终采用其容器的尺寸。
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>