this.speedY = -this.speedY;
}
if (this.y < 0) {//小球碰到上边界,纵坐标速度变为正
this.speedY = Math.abs(this.speedY);
}
ctx.drawImage(this.img, this.x, this.y, 60, 60);//绘制小球
}
}
主要是为扭蛋对象的原型添加上运动函数,运动函数的作用就是让扭蛋根据其速度动起来,并且在接触到边界的时候反弹。
初始化
接下来就是把扭蛋们放在扭蛋机里面:
function init() {//初始化
for (let i = 0; i < ballNum; i++) {//随机生成各色小球
let index = Math.floor(4 * Math.random());
awardList[i] = new Ball(index, ballList[index]);//新建小球对象
}
window.clearInterval(timer);//清除计时器
timer = setInterval(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);//清空画布
for (let i = 0; i < awardList.length; i++) {
awardList[i].run();
}//使小球运动
}, 15);
}这样子扭蛋机里面就已经有了小球。
开始扭蛋
开始扭蛋主要经历的过程就是点击按钮,扭蛋机扭蛋减少,获得相应扭蛋,中奖显示:
function play() {
if (awardList.length === 0) {//奖池中没有小球
alert('重新开始!');
init();
message.innerText = '点击抽奖';
} else {
window.clearInterval(timer);//清除计时器
let r = awardList.pop();//将奖池中的小球减少
timer = setInterval(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);//清空画布
for (let i = 0; i < awardList.length; i++) {
awardList[i].run();
}//使小球运动
}, 15);
switch (r.color) {//小球掉落动画
case 0:
award.setAttribute('class', 'dropBall1');
break;
case 1:
award.setAttribute('class', 'dropBall2');
break;
case 2:
award.setAttribute('class', 'dropBall3');
break;
case 3:
award.setAttribute('class', 'dropBall4');
break;
}
setTimeout(function () {//扭蛋成功提示
award.setAttribute('class', '');
switch (r.color) {
case 0:
message.innerText = '紫球!';
break;
case 1:
message.innerText = '绿球!';
break;
case 2:
message.innerText = '黄球!';
break;
case 3:
message.innerText = '红球!';
break;
}
}, 1100);
}
}
在这里扭蛋的掉落动画使用css动画的关键帧来完成:
.dropBall1 {content: "";position: absolute;left: 0;top: 0;width: 60px;height: 60px;display: block;background: url(../img/1.png) no-repeat;background-size: contain;animation: drop 1s ease-out forwards;-webkit-animation: drop 1s ease-out forwards;}
.dropBall2 {content: "";position: absolute;left: 0;top: 0;width: 60px;height: 60px;display: block;background: url(../img/2.png) no-repeat;background-size: contain;animation: drop 1s ease-out forwards;-webkit-animation: drop 1s ease-out forwards;}









