js实现图片抽奖
实现图片抽奖功能
图片抽奖功能可以通过随机选择图片并展示动画效果来实现。以下是一个完整的实现方案:
HTML结构
创建一个包含图片容器和抽奖按钮的简单HTML结构:
<div id="lottery-container">
<img id="result-image" src="placeholder.jpg" alt="抽奖结果">
</div>
<button id="start-lottery">开始抽奖</button>
CSS样式
为抽奖效果添加基本样式:
#lottery-container {
width: 300px;
height: 300px;
margin: 20px auto;
border: 2px solid #ccc;
}
#result-image {
width: 100%;
height: 100%;
object-fit: cover;
}
#start-lottery {
display: block;
margin: 0 auto;
padding: 10px 20px;
background-color: #ff4757;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
JavaScript实现
核心抽奖逻辑代码:
// 图片数组
const prizeImages = [
'image1.jpg',
'image2.jpg',
'image3.jpg',
'image4.jpg',
'image5.jpg'
];
// 获取DOM元素
const resultImage = document.getElementById('result-image');
const startButton = document.getElementById('start-lottery');
// 抽奖状态
let isLotteryRunning = false;
let animationInterval;
// 随机切换图片函数
function switchRandomImage() {
const randomIndex = Math.floor(Math.random() * prizeImages.length);
resultImage.src = prizeImages[randomIndex];
}
// 开始抽奖
function startLottery() {
if (isLotteryRunning) return;
isLotteryRunning = true;
startButton.disabled = true;
// 快速切换图片
animationInterval = setInterval(switchRandomImage, 100);
// 3秒后停止抽奖
setTimeout(stopLottery, 3000);
}
// 停止抽奖
function stopLottery() {
clearInterval(animationInterval);
isLotteryRunning = false;
startButton.disabled = false;
// 最终结果
const finalIndex = Math.floor(Math.random() * prizeImages.length);
resultImage.src = prizeImages[finalIndex];
alert(`恭喜获得奖品 ${finalIndex + 1}!`);
}
// 绑定事件
startButton.addEventListener('click', startLottery);
高级功能扩展
可以添加更多效果增强用户体验:
// 添加缓动动画效果
function stopLottery() {
clearInterval(animationInterval);
// 减速效果
let delay = 100;
const slowDownInterval = setInterval(() => {
switchRandomImage();
delay += 50;
if (delay > 500) {
clearInterval(slowDownInterval);
finalizeResult();
}
}, delay);
}
function finalizeResult() {
isLotteryRunning = false;
startButton.disabled = false;
const finalIndex = Math.floor(Math.random() * prizeImages.length);
resultImage.src = prizeImages[finalIndex];
// 使用动画显示结果
resultImage.style.transform = 'scale(1.2)';
setTimeout(() => {
resultImage.style.transform = 'scale(1)';
}, 300);
alert(`恭喜获得奖品 ${finalIndex + 1}!`);
}
注意事项
- 确保所有图片路径正确且可访问
- 可以根据需要调整抽奖持续时间
- 移动端适配可能需要调整样式
- 考虑添加加载状态避免图片未加载完成时显示问题
这个实现提供了基本的图片抽奖功能,可以根据具体需求进一步扩展和定制。







