Jun*_*Kim 5 javascript css chart.js
我正在使用 Chart.js,发现它style以不同的方式识别以下两个 s\xe2\x80\x94<canvas style="">效果很好,但<style>canvas{}扭曲了图表。这是两个例子。
<!doctype html>\n<html>\n\n<canvas id=Figure1 style="width:640px;height:480px"></canvas>\n\n<script src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js></script>\n<script>\nnew Chart(document.getElementById("Figure1"),{type:"scatter",data:{datasets:[{data:[{x:1,y:1},{x:2,y:2},{x:3,y:3}]}]},options:{responsive:false}});\n</script>\n</html>\nRun Code Online (Sandbox Code Playgroud)\n\n此代码不会扭曲图像,因此我想使用下面的代码全局应用设置。
\n\n<!doctype html>\n<html>\n\n<style>canvas{width:640px;height:480px}</style>\n\n<canvas id=Figure1></canvas>\n<script src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js></script>\n<script>\nnew Chart(document.getElementById("Figure1"),{type:"scatter",data:{datasets:[{data:[{x:1,y:1},{x:2,y:2},{x:3,y:3}]}]},options:{responsive:false}});\n</script>\n</html>\nRun Code Online (Sandbox Code Playgroud)\n\n我刚刚width:640px;height:480px在这段代码中重新定位,但它奇怪地拉伸了图像。我必须始终使用<canvas style="">来调整 Chart.js 图像的大小吗?
有多种方法可以指定画布的高度和宽度。但是您尝试的两种方法有什么区别?嗯,完整的解释可以在这里找到 Canvas 在使用 CSS 时会被拉伸,但在“宽度”/“高度”属性下正常
PS 您可以通过设置responsive: true 并将画布放入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,
}
});Run Code Online (Sandbox Code Playgroud)
/* If you change the wrapper's height and width, the chart will follow the wrapper's dimensions */
.wrapper{
height: 200px;
width: 300px;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)