【发布时间】: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();
<canvas id='canvas' width="500" height="500"></canvas>
【问题讨论】: