javascript - 调整窗口大小时调整画布大小 (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>
解决方案
您可以有一个回调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>
推荐阅读
- javascript - 如何确定访客是否在 Google 日历脚本中回答“是”?
- django - Django REST Framework,设置 Django Storages/S3 Boto 将一些媒体文件存储到存储桶,一些存储到本地存储
- mysql - 如何将sql结果作为对象获取
- windows - 使用 zip 命令指定与当前目录不同的路径
- javascript - HTML 第一行中出现意外的标记 < 我做错了什么?
- c++ - 修改类内的指针
- angular - 使用 Phoenix.js 连接 Angular 9
- azure - Asp.net 核心 API 服务器在本地测试时将事件记录到 Confluent Cloud Kafka,但在托管在 Azure 应用服务上时不记录
- javascript - 如何用更少的行数优化下面的代码?
- ios - 如何模拟 NSUbiquitousKeyValueStore 进行单元测试?