html转盘游戏,html5大转盘抽奖实例源码(基于vue.js)
时间: 2023-11-28 18:05:10 浏览: 138
以下是一个基于Vue.js的HTML5大转盘抽奖实例源码:
HTML部分:
```html
<div id="app">
<div class="wrapper">
<div class="pan-wrapper">
<canvas id="canvas" width="400" height="400"></canvas>
<img class="pointer" src="./assets/pointer.png" alt="pointer" @click="start" :class="{rotate: isStarted}">
</div>
<div class="result" v-if="!isStarted">
<p v-if="!prize">点击开始抽奖</p>
<p v-else-if="prize === '谢谢参与'">{{ prize }}</p>
<p v-else>恭喜您获得 {{ prize }}!</p>
</div>
</div>
</div>
```
CSS部分:
```css
.wrapper {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #eee;
}
.pan-wrapper {
position: relative;
}
.pointer {
position: absolute;
top: 130px;
left: 130px;
width: 140px;
cursor: pointer;
transition: all 3s ease;
}
.rotate {
transform: rotate(7200deg);
}
.result {
text-align: center;
margin-top: 20px;
font-size: 24px;
font-weight: bold;
}
```
JavaScript部分:
```js
new Vue({
el: '#app',
data: {
isStarted: false, // 是否已经开始抽奖
prizes: [
'一等奖',
'二等奖',
'三等奖',
'四等奖',
'五等奖',
'谢谢参与'
],
prize: null // 中奖结果
},
methods: {
start() {
if (this.isStarted) return;
this.isStarted = true;
this.prize = null;
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 绘制转盘
ctx.clearRect(0, 0, 400, 400);
ctx.beginPath();
ctx.arc(200, 200, 190, 0, 2 * Math.PI);
ctx.fillStyle = '#ffdd00';
ctx.fill();
for (let i = 0; i < this.prizes.length; i++) {
ctx.beginPath();
ctx.moveTo(200, 200);
ctx.arc(200, 200, 180, i * Math.PI / (this.prizes.length / 2), (i + 1) * Math.PI / (this.prizes.length / 2));
ctx.closePath();
ctx.fillStyle = i % 2 === 0 ? '#ffea00' : '#fff';
ctx.fill();
// 绘制文字
ctx.save();
ctx.translate(200, 200);
ctx.rotate(i * Math.PI / (this.prizes.length / 2) + (Math.PI / this.prizes.length));
ctx.fillStyle = '#f00';
ctx.font = 'bold 20px Arial';
ctx.fillText(this.prizes[i], 95, 5);
ctx.restore();
}
// 开始旋转
const rotate = () => {
const speed = 30; // 转盘旋转速度
let count = 0;
let timer = null;
const rotateFn = () => {
count += speed;
if (count >= 360) {
clearInterval(timer);
timer = null;
this.isStarted = false;
const index = Math.floor(Math.random() * this.prizes.length);
this.prize = this.prizes[index];
return;
}
ctx.translate(200, 200);
ctx.rotate(speed * Math.PI / 180);
ctx.translate(-200, -200);
this.isStarted && requestAnimationFrame(rotateFn);
};
timer = requestAnimationFrame(rotateFn);
};
rotate();
}
}
});
```
该实例使用了HTML5的Canvas绘制转盘,同时使用Vue.js实现了抽奖功能。用户点击“开始抽奖”按钮,转盘开始旋转。当转盘旋转一定角度后,随机产生一个中奖结果。实现过程中需要注意旋转的速度和旋转角度的计算。
阅读全文