繁体   English   中英

画布上的粒子是绘制的,但不是动画?

[英]Particles on canvas are drawn, but not animating?

尽管调用moveCircle()函数,但画布上的圆已绘制但没有运动。 在下面,您将找到带有属性的class Circle class CircleFactory ,用于生成具有这些属性的圆并将其存储到数组中的class CircleFactory以及用于遍历圆数组并负责绘制和移动它们的animate()函数。 。 请全屏运行代码段。

 //Canvas const canvas = document.getElementById('canvas'); //get Context const ctx = canvas.getContext('2d'); //Circle class class Circle { constructor(x, y, speedX, speedY){ this.x = x; this.y = y; this.r = 30; this.speedX = speedX; this.speedY = speedY; } } class CircleFactory { constructor(){ this.circles = []; } generateCircles(numOfCir){ const { circles } = this; for (let i = 0; i < numOfCir; i++) { let xPos = Math.random() * canvas.width; let yPos = Math.random() * canvas.height; const newCircle = new Circle( xPos, yPos, 1, -2); circles.push(newCircle); } } moveCircles({x, y, r, speedX, speedY}) { if (x + speedX > canvas.width - r || x + speedX < r) { speedX = -speedX; } if (y + speedY > canvas.height - r || y + speedY < r) { speedY = -speedY; } x += speedX; y += speedY; } drawCircles({x, y, r}) { ctx.beginPath(); ctx.strokeStyle = '#FF80AA'; ctx.arc(x, y, r, 0, Math.PI * 2 ); ctx.stroke(); } } const shape = new CircleFactory shape.generateCircles(2); const animate = () => { ctx.clearRect(0, 0, canvas.width, canvas.height); shape.circles.forEach(circle => { shape.moveCircles(circle); shape.drawCircles(circle); }) window.requestAnimationFrame(animate); } animate(); 
 <canvas id='canvas' width="500" height="500"></canvas> 

moveCircles({x, y, r, speedX, speedY}) ,由于您正在破坏圆形对象,因此您实际上并没有更新其状态,而只是在修改局部变量,随后将其丢弃。 而是将其编写为moveCircles(circle) ,并将坐标和速度称为circle.xcircle.y等。

暂无
暂无

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

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