在调整窗口大小时调整画布大小(JavaScript)

时间:2020-04-23 06:39:19

标签: javascript html css canvas

我想做什么

我想使画布的尺寸在整个窗口范围内。


问题是什么

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

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

The canvas size seems full

有效。


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

The canvas size doesn't change

我该怎么做才能在不更改球尺寸的情况下使画布的尺寸完全保持在窗口中?


这是我的代码

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>

1 个答案:

答案 0 :(得分:1)

您可以有一个回调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>