Что я хочу сделать
Я хочу, чтобы размер холста соответствовал окну.
В чем проблема
Я установил размер холста как указано ниже.
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>