This question already has answers here:
How can I scale the HTML5 canvas without making it blurry?
(3个答案)
去年关门了。
我想在画布上画一些长方形。这个画布应该是全屏的。
不调整画布大小的正确视图:
$(document).ready(() => {
  const canvas = $('#c')[0];
  const ctx = canvas.getContext('2d');
  ctx.lineWidth = 1;

  for (let i = 0; i < 10; i++) {
    const rectHeight = 100;
    const verticalPosition = i * rectHeight + (i + 1) * 10;
    ctx.strokeRect(10, verticalPosition, 200, rectHeight);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="c"></canvas>

具有调整大小的画布的视图:
$(document).ready(() => {
  const canvas = $('#c')[0];
  const ctx = canvas.getContext('2d');
  ctx.lineWidth = 1;

  for (let i = 0; i < 10; i++) {
    const rectHeight = 100;
    const verticalPosition = i * rectHeight + (i + 1) * 10;
    ctx.strokeRect(10, verticalPosition, 200, rectHeight);
  }
});

#c {
  width: 100%;
  height: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="c"></canvas>

我不想让元素变大。只是画布应该有更大的面积来绘制。画布上的元素应该保持它们的大小。否则它们会变得模糊。

最佳答案

您可以在JavaScript中声明画布widthheight。将尺寸设置为窗口的widthheight

$(document).ready(() => {
  const canvas = $('#c')[0];
  // Set the canvas size
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const ctx = canvas.getContext('2d');
  ctx.lineWidth = 1;

  for (let i = 0; i < 10; i++) {
    const rectHeight = 100;
    const verticalPosition = i * rectHeight + (i + 1) * 10;
    ctx.strokeRect(10, verticalPosition, 200, rectHeight);
  }
});

body {
  margin: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="c"></canvas>

09-16 10:19