Chart.js中的宽度和高度

5

我在使用Chart.js时发现它对以下两种style的处理方式不同——<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的图像尺寸吗?

1个回答

5

有许多方法可以指定画布的高度和宽度。但是你尝试的这两种方法之间有什么区别呢?那么,完整的解释可以在这里找到

P.S 如果将respsonsive: true设置为响应式,并将canvas放置在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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接