6

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?

Jonah
  • 1,495
  • 4
  • 17
  • 32
  • 1
    Possible duplicate of http://stackoverflow.com/questions/1664785/resize-html5-canvas-to-fit-window – andyderuyter Oct 17 '15 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 Oct 17 '15 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 Oct 17 '15 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 Oct 17 '15 at 22:12

2 Answers2

3

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

Jonah
  • 1,495
  • 4
  • 17
  • 32
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.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93