![](/img/trans.png)
[英]Animating a line drawn between 2 elements without canvas, linking by ID's
[英]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.x
, circle.y
等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.