给我写一份微信小程序大转盘前端代码,要求:每个人只能参与一次,前端可以控制奖品的抽奖率
时间: 2024-02-27 18:57:51 浏览: 146
以下是微信小程序大转盘前端代码示例,包含每个人只能参与一次和控制奖品抽奖率的功能。
HTML部分:
```
<view class="container">
<canvas canvas-id="canvas" class="canvas"></canvas>
<view class="btn" bindtap="startLottery">开始抽奖</view>
</view>
```
CSS部分:
```
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.canvas {
width: 80vw;
height: 80vw;
border-radius: 50%;
background-color: #fff;
}
.btn {
margin-top: 20px;
padding: 10px 20px;
font-size: 24px;
background-color: #f00;
color: #fff;
border: none;
border-radius: 5px;
}
.btn:hover {
cursor: pointer;
}
```
JS部分:
```
const app = getApp();
const prizes = [
{
name: "奖品1",
rate: 0.1
},
{
name: "奖品2",
rate: 0.2
},
{
name: "奖品3",
rate: 0.3
},
{
name: "奖品4",
rate: 0.4
}
];
const totalRate = prizes.reduce((acc, prize) => acc + prize.rate, 0);
Page({
data: {
canLottery: true,
prizeIndex: -1
},
onLoad: function () {
this.initCanvas();
},
initCanvas: function () {
const ctx = wx.createCanvasContext("canvas");
const width = app.globalData.systemInfo.windowWidth;
const height = app.globalData.systemInfo.windowHeight;
const radius = width * 0.4;
const centerX = width / 2;
const centerY = height * 0.4;
const angle = (2 * Math.PI) / prizes.length;
const colors = ["#ffc107", "#e91e63", "#9c27b0", "#2196f3"];
ctx.translate(centerX, centerY);
ctx.rotate(-Math.PI / 2);
prizes.forEach((prize, index) => {
const startAngle = index * angle;
const endAngle = (index + 1) * angle;
const gradient = ctx.createCircularGradient(0, 0, radius);
gradient.addColorStop(0, colors[index]);
gradient.addColorStop(1, "#fff");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.arc(0, 0, radius, startAngle, endAngle);
ctx.setFillStyle(gradient);
ctx.fill();
ctx.closePath();
ctx.save();
ctx.beginPath();
ctx.rotate(startAngle + angle / 2);
ctx.setFillStyle("#000");
ctx.setFontSize(20);
ctx.fillText(prize.name, -ctx.measureText(prize.name).width / 2, -radius * 0.8);
ctx.closePath();
ctx.restore();
});
ctx.draw();
},
startLottery: function () {
if (!this.data.canLottery) {
wx.showToast({
title: "您已参与过抽奖",
icon: "none"
});
return;
}
const random = Math.random() * totalRate;
let rate = 0;
let prizeIndex = -1;
for (let i = 0; i < prizes.length; i++) {
rate += prizes[i].rate;
if (random < rate) {
prizeIndex = i;
break;
}
}
if (prizeIndex === -1) {
wx.showToast({
title: "很遗憾,您未中奖",
icon: "none"
});
} else {
const prize = prizes[prizeIndex];
wx.showModal({
title: "恭喜您",
content: `获得了${prize.name}`,
showCancel: false
});
}
this.setData({
canLottery: false,
prizeIndex
});
}
});
```
在这个示例中,我们使用canvas绘制了一个圆形的大转盘,奖品和抽奖率通过prizes数组控制,totalRate表示所有奖品的抽奖率之和,startLottery函数用于随机选出中奖奖品并展示。另外,通过data中的canLottery和prizeIndex变量来控制每个人只能参与一次抽奖。
阅读全文