简体   繁体   中英

Particles on canvas are drawn, but not animating?

Circles on canvas are drawn but have no motion despite calling moveCircle() function. Below you'll find the class Circle with the properties, the class CircleFactory that generates the circles with those properties and stores them into an array, and the animate() function that iterates through the array of circles and is responsible for drawing and moving them. Please run the code snippet in full screen.

 //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> 

In moveCircles({x, y, r, speedX, speedY}) , because you're destructuring the circle object, you're not actually updating its state, you're just modifying local variables that are subsequently discarded. Instead, write it as moveCircles(circle) , and refer to the coordinates and speed as circle.x , circle.y , and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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