简体   繁体   中英

What length units can we use in JS?

I have created a canvas where I will draw shapes with the <canvas> tag, and its size is controlled by js. I want to resize it such as it covers the full desktop. However, units like vh and vw don't work here. Please suggest a way. Here's the js code:

var programCode = function(processingInstance) {
with (processingInstance) {
  size(400, 400); 
  frameRate(30);

}};

JS

Use window event resize:

window.addEventListener('resize', resizeCanvas, false);

You should use document.documentElement.clientHeight/Width because thay take scrollbar into consideration when window.innerHeight/Width do not.

By the way you can use this:

  let scrollHeight = window.innerWidth && document.documentElement.clientWidth ? 
  Math.min(window.innerWidth, document.documentElement.clientWidth) : 
  window.innerWidth || 
  document.documentElement.clientWidth || 
  document.getElementsByTagName('body')[0].clientWidth;

Or this:

let scrollHeight = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight );

You can just replace width and height words with each other in the above example

CSS

* { margin:0; padding:0; } /* to remove the top and left whitespace */

html, body { width:100%; height:100%; } /* just to be sure these are full screen*/

canvas { display:block; } /* To remove the scrollbars */

Use window.innerWidth and window.innerHeight to resize the canvas from JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM