答案:使用html5 canvas和鼠标事件实现拼图游戏,通过drawImage切割图片,结合mousedown、mousemove、mouseup模拟拖拽,打乱并重绘拼图块,设置吸附对齐与胜利判断逻辑完成交互。

用html5制作拼图游戏,核心是利用canvas绘图和拖放事件(Drag and Drop)的结合。整个过程不依赖外部库,纯前端实现,适合学习HTML5交互逻辑。
1. 页面结构与图片切分
使用canvas元素作为拼图绘制区域,并准备一张背景图用于切割成小块:
<canvas id="puzzle" width="400" height="400"></canvas> <img id="sourceImage" src="puzzle.jpg" style="display:none;">
将图片分为3×3的格子,每块大小为133×133像素(以400×400图为例)。通过context.drawImage()把原图切割并绘制到不同位置。
2. 图片分割与随机打乱
javaScript中先加载图片,再将其分割成9个片段,并打乱顺序模拟“洗牌”:
立即学习“前端免费学习笔记(深入)”;
const canvas = document.getElementById("puzzle"); const ctx = canvas.getContext("2d"); const img = document.getElementById("sourceImage"); <p>let pieces = []; const rows = 3, cols = 3; const pieceWidth = canvas.width / cols; const pieceHeight = canvas.height / rows;</p><p>// 切分图像并生成碎片数组 function initPuzzle() { for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { pieces.push({ x: col <em> pieceWidth, y: row </em> pieceHeight, correctX: col <em> pieceWidth, correctY: row </em> pieceHeight }); } } // 随机打乱碎片位置 pieces.sort(() => Math.random() - 0.5); drawPuzzle(); }</p>
3. 拖放事件实现拼图移动
为每个拼图块启用拖拽功能。HTML5原生支持draggable属性,但canvas绘制的内容默认不可拖。解决方案:在canvas上监听鼠标事件模拟拖拽。
关键步骤:
- 监听mousedown判断是否点击在某个拼图块上
- 监听mousemove实现拖动效果
- 监听mouseup完成放置并检查是否归位
let draggingPiece = null; let offsetX, offsetY; <p>canvas.addEventListener("mousedown", function(e) { const rect = canvas.getBoundingClientRect(); const mouseX = e.clientX - rect.left; const mouseY = e.clientY - rect.top;</p><pre class='brush:php;toolbar:false;'>// 查找被点击的拼图块 for (let i = pieces.length - 1; i >= 0; i--) { const p = pieces[i]; if (mouseX >= p.x && mouseX <= p.x + pieceWidth && mouseY >= p.y && mouseY <= p.y + pieceHeight) { draggingPiece = p; offsetX = mouseX - p.x; offsetY = mouseY - p.y; break; } }
});
canvas.addEventListener(“mousemove”, function(e) { if (!draggingPiece) return; const rect = canvas.getBoundingClientRect(); draggingPiece.x = e.clientX – rect.left – offsetX; draggingPiece.y = e.clientY – rect.top – offsetY; drawPuzzle(); // 实时重绘 });
canvas.addEventListener(“mouseup”, function() { if (!draggingPiece) return;
// 吸附对齐:判断是否靠近正确位置 const tolerance = 20; if (Math.abs(draggingPiece.x - draggingPiece.correctX) < tolerance && Math.abs(draggingPiece.y - draggingPiece.correctY) < tolerance) { draggingPiece.x = draggingPiece.correctX; draggingPiece.y = draggingPiece.correctY; } draggingPiece = null; drawPuzzle(); checkwin(); // 检查是否完成
});
4. 绘制与胜利判断
每次操作后调用drawPuzzle()重绘所有拼图块:
function drawPuzzle() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (let piece of pieces) { ctx.drawImage( img, piece.correctX, piece.correctY, pieceWidth, pieceHeight, piece.x, piece.y, pieceWidth, pieceHeight ); // 可选:加边框便于识别 ctx.strokeStyle = "#fff"; ctx.strokeRect(piece.x, piece.y, pieceWidth, pieceHeight); } } <p>function checkWin() { let win = true; for (let piece of pieces) { if (piece.x !== piece.correctX || piece.y !== piece.correctY) { win = false; break; } } if (win) { setTimeout(() => alert("拼图完成!"), 500); } }</p>
图片加载完成后启动游戏:
img.onload = function() { initPuzzle(); };
基本上就这些。通过canvas绘图、鼠标事件追踪和位置比对,就能实现一个可玩的拼图游戏。关键是理解如何把图像分块、拖动重绘以及判断对齐逻辑。不复杂但容易忽略细节,比如坐标转换和吸附容差。整体代码控制在200行内,适合初学者掌握HTML5交互应用。


