js实现划猪
实现划猪游戏的基本思路
划猪游戏通常指的是类似“刮刮乐”的互动效果,用户通过鼠标或触摸手势“刮开”涂层以显示隐藏内容。以下是使用JavaScript和HTML5 Canvas实现的基本方法。
HTML结构设置
创建基础的HTML结构,包含一个Canvas元素作为刮刮乐的画布区域:

<canvas id="scratchCanvas" width="300" height="300"></canvas>
<p id="resultText" style="display:none;">恭喜中奖!</p>
CSS样式调整
为Canvas添加基础样式,确保视觉效果:

#scratchCanvas {
border: 1px solid #000;
cursor: crosshair;
background-color: #ccc;
}
JavaScript核心逻辑
初始化Canvas并实现刮擦效果:
const canvas = document.getElementById('scratchCanvas');
const ctx = canvas.getContext('2d');
const resultText = document.getElementById('resultText');
let isDrawing = false;
// 初始化涂层
ctx.fillStyle = '#999';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = '20px Arial';
ctx.fillStyle = '#000';
ctx.fillText('刮开有奖', 100, 150);
// 事件监听
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
function startDrawing(e) {
isDrawing = true;
draw(e);
}
function draw(e) {
if (!isDrawing) return;
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// 使用合成模式实现刮擦效果
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x, y, 15, 0, Math.PI * 2);
ctx.fill();
checkCompletion();
}
function stopDrawing() {
isDrawing = false;
}
function checkCompletion() {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pixels = imageData.data;
let transparentCount = 0;
for (let i = 0; i < pixels.length; i += 4) {
if (pixels[i + 3] === 0) {
transparentCount++;
}
}
const transparency = transparentCount / (pixels.length / 4);
if (transparency > 0.5) {
resultText.style.display = 'block';
}
}
触摸屏适配
添加触摸事件支持以实现移动端兼容:
canvas.addEventListener('touchstart', handleTouch);
canvas.addEventListener('touchmove', handleTouch);
function handleTouch(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent(
e.type === 'touchstart' ? 'mousedown' : 'mousemove',
{
clientX: touch.clientX,
clientY: touch.clientY
}
);
canvas.dispatchEvent(mouseEvent);
}
进阶优化方案
- 性能优化:对于大尺寸Canvas,改用矩形区域检测替代全像素检测
- 视觉效果:添加粒子动画或渐变效果增强刮擦体验
- 奖品系统:集成随机奖品生成逻辑
- 重置功能:添加重新刮卡按钮
function resetScratch() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = '#999';
ctx.fillRect(0, 0, canvas.width, canvas.height);
resultText.style.display = 'none';
}
实现时需注意不同浏览器的兼容性问题,特别是触摸事件的处理。可根据实际需求调整刮擦灵敏度(透明阈值)和画笔大小。






