html 实现转盘抽奖代码
时间: 2023-11-28 13:05:35 浏览: 98
好的,以下是一个简单的HTML转盘抽奖代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>转盘抽奖</title>
<style>
#container {
position: relative;
width: 500px;
height: 500px;
}
#wheel {
position: absolute;
top: 0;
left: 0;
width: 500px;
height: 500px;
background: linear-gradient(to bottom, #ff0000 0%, #ff6600 100%);
border-radius: 50%;
z-index: 1;
overflow: hidden;
}
#pin {
position: absolute;
top: 50%;
left: 50%;
width: 60px;
height: 60px;
margin: -30px 0 0 -30px;
background-image: url('https://www.example.com/images/pin.png');
background-size: 100% 100%;
z-index: 2;
}
</style>
</head>
<body>
<div id="container">
<div id="wheel"></div>
<div id="pin"></div>
</div>
<script>
var angles = [0, 45, 90, 135, 180, 225, 270, 315];
var prizeNames = ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6', '奖品7', '奖品8'];
var prizeAngle = Math.floor(Math.random() * 360); // 随机奖品角度
var prizeIndex = Math.floor(prizeAngle / 45); // 奖品索引
var wheel = document.getElementById('wheel');
var pin = document.getElementById('pin');
wheel.style.transform = 'rotate(' + prizeAngle + 'deg)';
// 绘制扇形
for (var i = 0; i < angles.length; i++) {
var angle = angles[i];
var startAngle = angle + 2;
var endAngle = angle + 45 - 2;
var slice = document.createElement('div');
slice.style.position = 'absolute';
slice.style.top = '50%';
slice.style.left = '50%';
slice.style.width = '0';
slice.style.height = '0';
slice.style.borderTop = '250px solid transparent';
slice.style.borderBottom = '250px solid transparent';
slice.style.borderLeft = '250px solid #fff';
slice.style.transform = 'rotate(' + angle + 'deg)';
// 添加奖品
var prize = document.createElement('div');
prize.innerText = prizeNames[i];
prize.style.position = 'absolute';
prize.style.top = '50%';
prize.style.left = '50%';
prize.style.width = '200px';
prize.style.height = '20px';
prize.style.fontSize = '20px';
prize.style.fontWeight = 'bold';
prize.style.transform = 'translateY(-50%) translateX(-50%) rotate(' + (-angle) + 'deg)';
if (i == prizeIndex) {
slice.appendChild(prize);
}
wheel.appendChild(slice);
}
// 开始旋转
var rotating = false;
pin.addEventListener('click', function() {
if (rotating) return;
rotating = true;
var rotateAngle = prizeAngle + 1440; // 4圈
var duration = 5000; // 5秒
wheel.style.transition = 'transform ' + duration / 1000 + 's ease-in-out';
wheel.style.transform = 'rotate(' + rotateAngle + 'deg)';
setTimeout(function() {
alert('恭喜你获得了' + prizeNames[prizeIndex]);
rotating = false;
}, duration);
});
</script>
</body>
</html>
```
这段代码会创建一个转盘,并在转盘上绘制奖品,然后实现点击指针可以开始旋转,并最终停在一个随机的奖品上。你可以根据需要修改奖品的数量、名称、样式等。如果你有任何疑问,请随时问我!
阅读全文