给我一个JavaScript的代码,实现随机转盘抽人,能实时显示名字的
时间: 2023-06-05 11:08:10 浏览: 206
抽奖效果。
下面是一个前端实现的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>随机转盘抽奖</title>
<style>
#turntable{
position: relative;
margin: 100px auto;
width: 300px;
height: 300px;
background: url(turntable.png) no-repeat;
background-size: 100% 100%;
}
.arrow{
position: absolute;
left: 135px;
top: 35px;
width: 0;
height: 0;
border: 70px solid transparent;
border-bottom: 80px solid red;
transform-origin: center bottom;
transform: rotateZ(-30deg);
animation: rotate 3s ease-out infinite;
animation-play-state: paused;
}
@keyframes rotate{
to{
transform: rotateZ(330deg);
}
}
#winner{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 30px;
color: red;
opacity: 0;
transition: opacity 1s;
}
</style>
</head>
<body>
<div id="turntable">
<div class="arrow"></div>
</div>
<div id="winner"></div>
<button onclick="start()">开始抽奖</button>
<script>
var names = ["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"];
var angle = 0; //转盘初始角度
var unitAngle = 360 / names.length; //每个奖项对应的角度
var winnerIndex = null; //获奖者的索引
//开始转动转盘
function start() {
if (winnerIndex !== null) {
alert("已经抽过奖啦,不要重复操作!");
return;
}
var minRound = 2; //最小旋转圈数
var maxRound = 8; //最大旋转圈数
angle = 0;
winnerIndex = parseInt(Math.random() * names.length); //随机获奖者索引
var round = minRound + parseInt(Math.random() * (maxRound - minRound + 1));
//计算需要旋转的角度
var finalAngle = 360 * round + (winnerIndex + 0.5) * unitAngle;
console.log("需要旋转的角度:" + finalAngle);
//更新转盘角度,开始旋转
var turntable = document.getElementById("turntable");
turntable.style.transform = "rotate(" + angle + "deg)";
turntable.style.transition = "transform 3s ease-out";
turntable.addEventListener("transitionend", showWinner);
//更新箭头角度,继续通过CSS动画旋转
var arrow = document.querySelector(".arrow");
arrow.style.animationPlayState = "running";
arrow.style.transform = "rotateZ(-30deg)"; //初始角度
setTimeout(function(){
angle = finalAngle;
turntable.style.transform = "rotate(" + angle + "deg)";
}, 50);
//显示中奖者姓名
function showWinner() {
turntable.removeEventListener("transitionend", showWinner);
console.log("中奖者:" + names[winnerIndex]);
document.getElementById("winner").innerText = "恭喜 " + names[winnerIndex] + " 中奖!";
document.getElementById("winner").style.opacity = 1;
}
}
</script>
</body>
</html>
```
需要注意的是,上面的代码中使用了一个转盘图片(turntable.png),需要将其放在与HTML文件同级的目录下。此外,代码中也包含了一些CSS动画和过渡效果,可以通过调整相关参数来修改转盘的样式和旋转的速度。
阅读全文