繁体   English   中英

如何删除HTML 5 canvas中的形状?

[英]How to delete shapes in HTML 5 canvas?

我创建了此功能来绘制圆形:

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来完成此操作。然后在此基础上进行make和if / else语句。

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

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

处理此问题的方法是每帧重新绘制画布。
在帧的开头,清除画布,然后重新绘制对象。 这样,在简单的数据结构(如数组)中管理对象变得非常容易。

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM