gpt4 book ai didi

javascript - 如何删除 HTML 5 Canvas 中的形状?

转载 作者:行者123 更新时间:2023-11-30 14:18:31 27 4
gpt4 key购买 nike

我创建了这个函数来绘制圆圈:

function draw(x, y, m) {
i += 1;
c.beginPath();
c.arc(x, y, m, 0, Math.PI * 2, false);
c.strokeStyle = 'white';
c.stroke();
c.fillStyle = "white";
c.fill();
}

我用它通过这个函数在随机位置创建圆圈:

function animator() {
var x = Math.random() * window.innerWidth;
var y = Math.random() * window.innerHeight;
var m = Math.floor(Math.random() * 5)

window.requestAnimationFrame(animator);

draw(x, y, m);
}

这将继续添加圈子。但是,最终当达到 200 个圆圈时,每次添加新形状时我都想删除 1 个形状。我的想法是通过将 i 加起来直到达到 200 来做到这一点。然后根据它制作和 if/else 语句。

for (var i = 0; i < 200; i++) {
draw();
}

但是,我不知道如何删除形状。

最佳答案

处理此问题的方法是每帧重新绘制 Canvas 。
在框架的开头,您清除 Canvas ,然后重新绘制对象。这样一来,管理数组等简单数据结构中的对象就变得非常容易。

const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');

function getRandomNumber(min, max) {
return Math.random() * (max - min) + min;
}

class Circle {
constructor(centerX, centerY, radius) {
this.centerX = centerX;
this.centerY = centerY;
this.radius = radius;
}

draw() {
context.beginPath();
context.arc(this.centerX, this.centerY, this.radius, 0, 2 * Math.PI, false);
context.fillStyle = 'white';
context.fill();
context.lineWidth = 2;
context.strokeStyle = 'red';
context.stroke();
}
}

function createRandomCircle() {
const x = getRandomNumber(0, canvas.width);
const y = getRandomNumber(0, canvas.height);
const r = getRandomNumber(5, 10);

return new Circle(x, y, r);
}

// We manage all circles here
const circles = [];

function gameLoop() {
// Clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);

if (circles.length > 200) {
circles.shift();
}

// Add a circle
circles.push(createRandomCircle());

// Let every object draw itself
circles.forEach(c => c.draw());
}

// Start the loop
window.setInterval(gameLoop, 50);
canvas {
width: 100%;
height: 100%;
background: black;
}
<canvas></canvas>

关于javascript - 如何删除 HTML 5 Canvas 中的形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53141763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com