扭蛋机为多小球在一个区域范围内移动碰撞
先初始化Canvas 然后用 drawImage 渲染出一个小球
ctx.drawImage(this.img, this.x, this.y, 60, 60);
改变小球的 x, y 位置即可以实现小球运动
写一个定时器, 隔 16ms 执行一次, 即60帧
timer = setInterval(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.x += this.speedX;
this.y += this.speedY;
// 小球碰到右边界,横坐标速度变为负
if (this.x > canvas.width - this.r * 2) {
this.speedX = -this.speedX;
}
// 小球碰到左边界,横坐标速度变为正
if (this.x < 0) {
this.speedX = Math.abs(this.speedX);
}
// 小球碰到下边界,纵坐标速度变为负
if (this.y > canvas.height - this.r * 2) {
this.speedY = -this.speedY;
}
// 小球碰到上边界,纵坐标速度变为正
if (this.y < 0) {
this.speedY = Math.abs(this.speedY);
}
ctx.drawImage(this.img, this.x, this.y, 60, 60);
}, 16);
再把小球封装成class 加入数组控制。 就能实现扭蛋机的效果