js实现图片抽奖
实现图片抽奖功能
使用JavaScript实现图片抽奖功能可以通过随机选择图片并展示的方式完成。以下是实现该功能的几种方法:
基本实现方法
准备一组图片URL或DOM元素,通过随机数选择其中一个展示。
const images = [
'image1.jpg',
'image2.jpg',
'image3.jpg',
'image4.jpg'
];
function drawImage() {
const randomIndex = Math.floor(Math.random() * images.length);
const resultImage = document.getElementById('result-image');
resultImage.src = images[randomIndex];
}
动画效果增强
添加旋转动画效果使抽奖过程更生动。
let isRotating = false;
let rotateInterval;
function startRotation() {
if (isRotating) return;
isRotating = true;
let currentIndex = 0;
rotateInterval = setInterval(() => {
currentIndex = (currentIndex + 1) % images.length;
document.getElementById('result-image').src = images[currentIndex];
}, 100);
}
function stopRotation() {
clearInterval(rotateInterval);
isRotating = false;
const finalIndex = Math.floor(Math.random() * images.length);
document.getElementById('result-image').src = images[finalIndex];
}
概率控制实现
为不同图片设置不同的中奖概率。

const weightedImages = [
{ src: 'image1.jpg', weight: 10 },
{ src: 'image2.jpg', weight: 30 },
{ src: 'image3.jpg', weight: 50 },
{ src: 'image4.jpg', weight: 10 }
];
function weightedDraw() {
const totalWeight = weightedImages.reduce((sum, item) => sum + item.weight, 0);
let random = Math.random() * totalWeight;
for (const item of weightedImages) {
if (random < item.weight) {
document.getElementById('result-image').src = item.src;
return;
}
random -= item.weight;
}
}
完整HTML示例
<!DOCTYPE html>
<html>
<head>
<title>图片抽奖</title>
<style>
#result-image {
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
button {
padding: 10px 20px;
font-size: 16px;
margin-top: 20px;
}
</style>
</head>
<body>
<img id="result-image" src="placeholder.jpg" alt="抽奖结果">
<button onclick="startRotation()">开始抽奖</button>
<button onclick="stopRotation()">停止</button>
<script>
const images = [
'image1.jpg',
'image2.jpg',
'image3.jpg',
'image4.jpg'
];
let isRotating = false;
let rotateInterval;
function startRotation() {
if (isRotating) return;
isRotating = true;
let currentIndex = 0;
rotateInterval = setInterval(() => {
currentIndex = (currentIndex + 1) % images.length;
document.getElementById('result-image').src = images[currentIndex];
}, 100);
}
function stopRotation() {
clearInterval(rotateInterval);
isRotating = false;
const finalIndex = Math.floor(Math.random() * images.length);
document.getElementById('result-image').src = images[finalIndex];
}
</script>
</body>
</html>
注意事项
- 确保图片路径正确,建议使用绝对路径或确保相对路径准确
- 对于大量图片考虑预加载,避免抽奖时出现加载延迟
- 移动端适配可能需要调整图片尺寸和按钮样式
- 抽奖算法可根据实际需求调整,如设置特定奖项的中奖概率






