admin管理员组

文章数量:1401681

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?

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?

Share Improve this question asked Oct 17, 2015 at 21:43 JonahJonah 1,5454 gold badges17 silver badges34 bronze badges 4
  • 1 Possible duplicate of stackoverflow./questions/1664785/… – andyderuyter Commented Oct 17, 2015 at 21:46
  • You should set the number of pixels with width and height attributes, whose value is an integer. Then, you can distort it with CSS. – Oriol Commented Oct 17, 2015 at 21:57
  • @Oriol That just stretches the image for me. How can I go about setting the width and height attributes as proportions of the view port? – Jonah Commented Oct 17, 2015 at 22:10
  • @Oriol Never mind, just realised I can easily use document.documentElement.clientWidth and document.documentElement.clientHeight instead of using vw/vh – Jonah Commented Oct 17, 2015 at 22:12
Add a ment  | 

2 Answers 2

Reset to default 3

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

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.

本文标签: javascriptCan I specify canvas dimensions using vh and vwStack Overflow