js实现刮刮卡

实现刮刮卡效果
使用HTML5 Canvas和JavaScript可以轻松实现刮刮卡效果。以下是具体实现方法:
基础HTML结构
<canvas id="scratchCanvas" width="300" height="150"></canvas>
<div id="prize" style="display:none;">恭喜中奖!</div>
CSS样式
#scratchCanvas {
border: 1px solid #000;
cursor: crosshair;
}
#prize {
position: absolute;
top: 50px;
left: 50px;
font-size: 24px;
color: red;
}
JavaScript实现
const canvas = document.getElementById('scratchCanvas');
const ctx = canvas.getContext('2d');
const prize = document.getElementById('prize');
let isDrawing = false;
// 初始化画布
function initCanvas() {
ctx.fillStyle = '#ccc';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#666';
ctx.font = '20px Arial';
ctx.fillText('刮开此处查看结果', 50, 75);
}
// 绘制覆盖层
function drawCover() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = '#ddd';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
// 处理鼠标/触摸事件
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
// 触摸设备支持
canvas.addEventListener('touchstart', handleTouch);
canvas.addEventListener('touchmove', handleTouch);
canvas.addEventListener('touchend', stopDrawing);
function startDrawing(e) {
isDrawing = true;
draw(e);
}
function draw(e) {
if (!isDrawing) return;
const rect = canvas.getBoundingClientRect();
const x = (e.clientX || e.touches[0].clientX) - rect.left;
const y = (e.clientY || e.touches[0].clientY) - rect.top;
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x, y, 15, 0, Math.PI * 2);
ctx.fill();
checkScratchPercentage();
}
function handleTouch(e) {
e.preventDefault();
if (e.type === 'touchstart') {
startDrawing(e);
} else if (e.type === 'touchmove') {
draw(e);
}
}
function stopDrawing() {
isDrawing = false;
}
// 检查刮开比例
function checkScratchPercentage() {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pixels = imageData.data;
let transparentPixels = 0;
for (let i = 0; i < pixels.length; i += 4) {
if (pixels[i + 3] === 0) {
transparentPixels++;
}
}
const percentage = (transparentPixels / (canvas.width * canvas.height)) * 100;
if (percentage > 50) {
prize.style.display = 'block';
}
}
// 初始化
initCanvas();
drawCover();
实现原理说明
- 使用Canvas绘制覆盖层作为刮刮卡的遮盖部分
- 通过设置
globalCompositeOperation = 'destination-out'实现擦除效果 - 监听鼠标/触摸事件来触发擦除动作
- 定期检查透明像素比例,当超过阈值时显示奖品
进阶优化方向
- 添加刮开音效增强用户体验
- 实现重置功能,允许用户重新刮卡
- 使用更复杂的覆盖图案(如纹理图片)代替纯色
- 添加动画效果,如刮开时的粒子效果
- 支持移动端手势优化
移动端适配要点
- 添加
touch事件处理确保移动设备兼容性 - 防止触摸事件的默认行为避免页面滚动
- 适当调整画布大小以适应不同屏幕
- 增加触摸反馈效果
通过以上代码和说明,可以快速实现一个基础的刮刮卡效果,并可根据需求进行进一步扩展和优化。






