几乎每年快过年的时候,我都要为公司写一个抽奖小游戏,而且每次抽奖我都能中奖,记得有一年我拿到二百多的号码,结果中了二等奖,奖品是一个挂烫机。有一年拿到三百多的号码,中了三等奖,奖品是一个床上四件套。搞得同事们都以为我给自己开了buff,天地良心,年会入场的时候我和大家一样随机拿了入场券,我哪知道自己的号码是多少,只能说劳动的人运气都不会太差。
那些页面都喜气冲天,还带有公司logo,不适合放上来,这里放一个很简单的转盘抽奖小游戏吧。
点击图片看效果。
功能:
1、页面的布局需要一点技巧。
2、随机数的应用。
3、根据得到的随机数执行转盘的旋转角度。
4、用anime.js实现动画效果
5、lottery.js构造转盘实例并配置参数
6、点击按钮,就可以试试啦
核心代码:
<script src="js/jquery.min.js"></script>
<script src="js/anime.min.js"></script>
<script src="js/lottery.js"></script>
<script>
const oBtnPlay = document.querySelector('.fy-play');
const oResult = document.querySelector('.fy-result');
const oList = document.querySelectorAll('.fy-list');
// 创建构造函数的实例
const Lottery = Turntable.create();
// 点击按钮开始抽奖
oBtnPlay.onclick = function () {
// 清空中奖的结果
oResult.innerHTML = '';
// 产生[0,5]的随机数,一共6个奖项,每一个数字对应一个奖项
// [0,50]
let num = Math.floor(Math.random() * (50 - 0 + 1) + 0);
// console.log(Math.floor(Math.random()*10));
console.log(num);
if (num <= 5) {
num = num;
} else if (num > 5 && num < 10) {
num = 3;
} else if (num > 15 && num < 20) {
num = 1;
} else if (num > 30 && num < 40) {
num = 5;
} else {
num = 2;
}
// 使用了插件,传入num值,转盘会转到对应的位置,并执行回调函数
Lottery.start(num, function (index) {
// 获取中奖的结果
let result = oList[index].children[0].innerHTML;
// 显示在页面上
oResult.innerHTML = result;
});
}
</script>// lottery.js
var Turntable = (function () {
function Turntable(opts) {
_classCallCheck(this, Turntable);
this.opts = $.extend(true, {
target: '.lottery-wrap', // 旋转对象
easing: 'easeInOutSine', // anime.js 动画曲线
isplay: false, // 动画是否在播放
duration: 3000, // 动画时长
rotateNum: 5, // 旋转圈数
total: 6, // 奖励个数
offset: 0}, // 旋转偏移值
opts);
this.opts.angle = 360 / this.opts.total; // 旋转角度
}
_createClass(Turntable, [{
key: 'start',
value: function start(index, cb) {
this.opts.isplay = true;
var self = this,
opt = this.opts,
angle = opt.angle,
off = (opt.total - index) * angle - angle / 2 - opt.offset;
aniLottery = anime({
targets: this.opts.target,
easing: this.opts.easing,
autoplay: false,
duration: this.opts.duration,
rotate: opt.rotateNum * 360 + off,
complete: function complete() {
$(self.opts.target).css({
'-webkit-transform': 'rotate(' + off + 'deg)',
'transform': 'rotate(' + off + 'deg)'
});
self.stop();
cb && cb(index);
}
});
aniLottery.restart();
}
}, {
key: 'stop',
value: function stop() {
this.opts.isplay = false;
aniLottery.pause();
}
}], [{
key: 'create',
value: function create(opts) {
return new Turntable(opts);
}
}]);
return Turntable;
})();
发表评论:
◎请发表你卖萌撒娇或一针见血的评论,严禁小广告。