Can I specify canvas dimensions using vh and vw?

南笙酒味 提交于 2021-02-08 19:43:13

问题


My code is:

var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.canvas.width = 40vw;
ctx.canvas.height = 40vh;

and it doesn't work. Is it possible to use vw and vh when setting canvas dimensions in JavaScript? If so, how?


回答1:


I realised I could use document.documentElement.clientWidth and document.documentElement.clientHeight to work out the vw and vh respectively.




回答2:


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();

This perfectly sets up your HTML canvas to draw on, in a responsive manner too.



来源:https://stackoverflow.com/questions/33191909/can-i-specify-canvas-dimensions-using-vh-and-vw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!