我可以使用vh和vw指定画布尺寸吗?

Can I specify canvas dimensions using vh and vw?

本文关键字:布尺寸 vw 可以使 vh 我可以      更新时间:2023-09-26
我的代码是:
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.canvas.width = 40vw;
ctx.canvas.height = 40vh;

不起作用。在JavaScript中设置画布尺寸时,是否可以使用vw和vh ?如果有,怎么做?

我意识到我可以使用document.documentElement.clientWidthdocument.documentElement.clientHeight分别计算出vw和vh。

HTML:

<canvas class="canvas_hangman"></canvas> 

JS:

function setUpCanvas() {
  canvas = document.getElementsByClassName("canvas_hangman")[0];
  ctx = canvas.getContext('2d');
  ctx.translate(0.5, 0.5);
  // Set display size (vw/vh).
  var sizeWidth = 80 * window.innerWidth / 100,
    sizeHeight = 100 * window.innerHeight / 100 || 766;
  //Setting the canvas site and width to be responsive 
  canvas.width = sizeWidth;
  canvas.height = sizeHeight;
  canvas.style.width = sizeWidth;
  canvas.style.height = sizeHeight;
}
window.onload = setUpCanvas();

这完美地设置了你的HTML画布,以一种响应的方式。