【问题标题】:Particles on canvas are drawn, but not animating?画布上的粒子被绘制,但没有动画?
【发布时间】:2018-05-28 06:14:49
【问题描述】:

尽管调用了 moveCircle() 函数,画布上的圆圈已绘制,但没有运动。下面你会发现 class Circle 带有属性,class CircleFactory 生成具有这些属性的圆圈并将它们存储到一个数组中,以及 animate() 函数迭代圆数组并负责绘制和移动它们。请全屏运行代码sn-p。

//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();
&lt;canvas id='canvas' width="500" height="500"&gt;&lt;/canvas&gt;

【问题讨论】:

    标签: javascript html5-canvas


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 2016-11-22
      相关资源
      最近更新 更多