首页 > 解决方案 > 调整窗口大小时调整画布大小 (JavaScript)

问题描述

我想做的事

我想将画布大小保持在窗口中。


问题是什么

我如下所述设置画布大小。

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

画布大小似乎已满

有效。


但是当我调整窗口大小时,画布大小没有改变,而是保持其初始大小。

画布大小不变

我应该怎么做才能在不改变球大小的情况下保持画布大小完全到窗口?


这是我的代码

const canvas = document.querySelector('#sandBox');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');

class Circle {
  constructor(x, y, r, c) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.c = c;
  }

  draw() {
    ctx.beginPath();
    ctx.fillStyle = this.c;
    ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
    ctx.fill();
    ctx.closePath();
  }
}

const balls = [];

for (let i = 0; i < 20; i++) {
  let r = Math.floor(Math.random() * 30) + 15;
  let x = Math.random() * (canvas.width - r * 2) + r;
  let y = Math.random() * (canvas.height - r * 2) + r;
  let c = 'rgba(255,255,255,0.2)';
  balls.push(new Circle(x, y, r, c));
}

balls.forEach(ball => ball.draw());
body {
  position: relative;
}

canvas {
  /* width: 100vw;
  height: 100vh; */
  background-color: #393939;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}
<canvas id="sandBox"></canvas>

标签: javascripthtmlcsscanvas

解决方案


您可以有一个回调onresize并使用它来重新创建画布:

每次调整窗口大小时,您都必须重新绘制画布,除非您将其保存在某处。

function init() {
  const canvas = document.querySelector("#sandBox");
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const ctx = canvas.getContext("2d");

  class Circle {
    constructor(x, y, r, c) {
      this.x = x;
      this.y = y;
      this.r = r;
      this.c = c;
    }

    draw() {
      ctx.beginPath();
      ctx.fillStyle = this.c;
      ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
      ctx.fill();
      ctx.closePath();
    }
  }

  const balls = [];

  for (let i = 0; i < 20; i++) {
    let r = Math.floor(Math.random() * 30) + 15;
    let x = Math.random() * (canvas.width - r * 2) + r;
    let y = Math.random() * (canvas.height - r * 2) + r;
    let c = "rgba(255,255,255,0.2)";
    balls.push(new Circle(x, y, r, c));
  }

  balls.forEach((ball) => ball.draw());
}

window.onload = function() {
  init();
};
body {
  position: relative;
}

canvas {
  width: 100vw;
  height: 100vh;
  background-color: #393939;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}
<body onresize="init()">
  <canvas id="sandBox"></canvas>
</body>


推荐阅读