基础概念: 刮刮乐是一种常见的互动游戏,用户通过刮擦涂层来显示隐藏的信息或奖励。在前端开发中,可以使用JavaScript和CSS来模拟这种效果。
相关优势:
类型:
应用场景:
示例代码: 以下是一个简单的刮刮乐实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>刮刮乐</title>
<style>
#scratchArea {
width: 200px;
height: 100px;
background: #ccc;
position: relative;
cursor: pointer;
}
#scratchCanvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
}
#reward {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: #fff;
background: rgba(0, 0, 0, 0.7);
}
</style>
</head>
<body>
<div id="scratchArea">
<canvas id="scratchCanvas"></canvas>
<div id="reward">恭喜中奖!</div>
</div>
<script>
const scratchArea = document.getElementById('scratchArea');
const scratchCanvas = document.getElementById('scratchCanvas');
const ctx = scratchCanvas.getContext('2d');
const reward = document.getElementById('reward');
scratchCanvas.width = scratchArea.offsetWidth;
scratchCanvas.height = scratchArea.offsetHeight;
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height);
let isDrawing = false;
scratchArea.addEventListener('mousedown', () => {
isDrawing = true;
ctx.beginPath();
});
scratchArea.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
});
scratchArea.addEventListener('mouseup', () => {
isDrawing = false;
});
scratchArea.addEventListener('touchstart', (e) => {
e.preventDefault();
const touch = e.touches[0];
const rect = scratchArea.getBoundingClientRect();
const offsetX = touch.clientX - rect.left;
const offsetY = touch.clientY - rect.top;
scratchArea.dispatchEvent(new MouseEvent('mousedown', { clientX: offsetX, clientY: offsetY }));
});
scratchArea.addEventListener('touchmove', (e) => {
e.preventDefault();
const touch = e.touches[0];
const rect = scratchArea.getBoundingClientRect();
const offsetX = touch.clientX - rect.left;
const offsetY = touch.clientY - rect.top;
scratchArea.dispatchEvent(new MouseEvent('mousemove', { clientX: offsetX, clientY: offsetY }));
});
scratchArea.addEventListener('touchend', (e) => {
e.preventDefault();
scratchArea.dispatchEvent(new MouseEvent('mouseup'));
});
scratchCanvas.addEventListener('click', () => {
if (ctx.getImageData(0, 0, scratchCanvas.width, scratchCanvas.height).data.every((val) => val === 255)) {
reward.style.display = 'flex';
}
});
</script>
</body>
</html>
常见问题及解决方法:
e.preventDefault()
防止默认行为。通过以上代码和解决方法,你可以轻松实现一个基本的刮刮乐效果。根据具体需求,还可以进一步优化和扩展功能。
领取专属 10元无门槛券
手把手带您无忧上云