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

时间:2018-05-27 22:07:52

标签: javascript html5-canvas

画布上的圆圈虽然调用了moveCircle()函数但是没有运动。您可以在下方找到包含属性的class Circle,使用这些属性生成圆圈的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>

1 个答案:

答案 0 :(得分:0)

moveCircles({x, y, r, speedX, speedY})中,由于您正在对圈子对象进行解构,您实际上并未更新其状态,因此您只需修改随后被丢弃的局部变量。相反,请将其写为moveCircles(circle),并将坐标和速度称为circle.xcircle.y,等等。