我们可以在 JS 中使用哪些长度单位?

What length units can we use in JS?

我创建了一个canvas,我将在其中使用<canvas>标签绘制形状,其大小由js控制。我想调整它的大小,使其覆盖整个桌面。但是,像 vh 和 vw 这样的单位在这里不起作用。请提出一个方法。这是js代码:

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

}};

使用 window.innerWidthwindow.innerHeight 从 JavaScript 调整 canvas 的大小。

JS

使用 window 事件调整大小:

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

您应该使用 document.documentElement.clientHeight/Width,因为当 window.innerHeight/Width 不考虑滚动条时。

顺便说一句,你可以使用这个:

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

或者这个:

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

你可以在上面的例子中将宽度和高度单词相互替换

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 */