javascript - Can I specify canvas dimensions using vh and vw? - Stack Overflow

My code is:var canvas = document.getElementById("canvas");ctx = canvas.getContext("2d&q

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744232351a4564315.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信