HTML画布在全屏大小上变得模糊

时间:2018-06-18 08:11:25

标签: javascript jquery html css 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);
  }
});
<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>

我不希望元素变大。只是画布应该有更大的区域可供使用。画布上的元素应保持其大小。否则他们会变得模糊。

3 个答案:

答案 0 :(得分:5)

您可以在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>

答案 1 :(得分:1)

我遇到了同样的问题,只需将widthheight属性设置为canvas元素的offsetWidthoffsetHeight属性即可解决问题。画布的内部尺寸是根据widthheight属性计算出来的,并且令人惊讶的是,它们未通过在CSS中将它们设置为100%来设置。所以你的工作代码是:

$(document).ready(() => {
  const canvas = $('#c')[0];
  const ctx = canvas.getContext('2d');
  canvas.width = canvas.offsetWidth;
  canvas.height = canvas.offsetHeight;
  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>

度过愉快的一天。

答案 2 :(得分:-3)

我认为这是CSS的常见问题。我宁愿使用JS:

canvas.width = document.body.clientWidth; 
canvas.height = document.body.clientHeight;