將一張圖片切割為 N×M 個矩形塊,以十字交叉線動畫「切開」畫面,再將碎片重組或散開。核心技術:CanvasRenderingContext2D.drawImage() 切片繪製、CSS Transform 動畫、請求動畫幀循環。
function sliceImage(image, cols, rows) {
const pieces = [];
const pieceW = image.width / cols;
const pieceH = image.height / rows;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const canvas = document.createElement("canvas");
canvas.width = pieceW;
canvas.height = pieceH;
const ctx = canvas.getContext("2d");
// 從原圖切取對應區域繪製到小畫布
ctx.drawImage(
image,
col * pieceW, row * pieceH, pieceW, pieceH, // 源矩形
0, 0, pieceW, pieceH // 目標矩形
);
pieces.push({
canvas,
col, row,
x: col * pieceW, // 原始位置
y: row * pieceH,
// 動畫屬性
tx: 0, ty: 0, // 位移
rx: 0, ry: 0, rz: 0, // 旋轉
scale: 1,
opacity: 1
});
}
}
return pieces;
}
class ImageSlicer {
constructor(container, imageSrc, cols = 5, rows = 5) {
this.container = container;
this.cols = cols;
this.rows = rows;
this.pieces = [];
this.animating = false;
this.crosshair = { x: 0, y: 0, progress: 0 }; // 切割線進度
this.loadImage(imageSrc).then(img => this.init(img));
}
loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "anonymous"; // 支援跨域
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
}
init(image) {
this.image = image;
this.container.innerHTML = "";
this.container.style.position = "relative";
this.container.style.width = image.width + "px";
this.container.style.height = image.height + "px";
// 建立碎片 DOM
this.pieces = this.createPieces(image);
this.pieces.forEach(p => this.container.appendChild(p.el));
// 切割線元素
this.lineX = this.createLine("horizontal");
this.lineY = this.createLine("vertical");
this.container.appendChild(this.lineX);
this.container.appendChild(this.lineY);
}
createPieces(image) {
const pieceW = image.width / this.cols;
const pieceH = image.height / this.rows;
const pieces = [];
for (let r = 0; r < this.rows; r++) {
for (let c = 0; c < this.cols; c++) {
const canvas = document.createElement("canvas");
canvas.width = pieceW;
canvas.height = pieceH;
const ctx = canvas.getContext("2d");
ctx.drawImage(image, c * pieceW, r * pieceH, pieceW, pieceH, 0, 0, pieceW, pieceH);
const el = document.createElement("div");
el.className = "slice-piece";
el.style.cssText = `
position: absolute; left: ${c * pieceW}px; top: ${r * pieceH}px;
width: ${pieceW}px; height: ${pieceH}px;
transform-origin: center center;
will-change: transform, opacity;
`;
el.appendChild(canvas);
pieces.push({
el, canvas, ctx,
col: c, row: r,
origX: c * pieceW, origY: r * pieceH,
tx: 0, ty: 0, rot: 0, scale: 1, opacity: 1,
delay: (r * this.cols + c) * 20 // 錯開動畫延遲
});
}
}
return pieces;
}
createLine(orientation) {
const line = document.createElement("div");
line.className = `slice-line slice-line-${orientation}`;
line.style.cssText = `
position: absolute; background: #ffcc00; z-index: 10; pointer-events: none;
${orientation === "horizontal"
? "width: 100%; height: 4px; left: 0; top: 0;"
: "width: 4px; height: 100%; left: 0; top: 0;"}
transform: ${orientation === "horizontal" ? "scaleY(0)" : "scaleX(0)"};
transform-origin: ${orientation === "horizontal" ? "center top" : "left center"};
transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
`;
return line;
}
// 核心動畫序列
async sliceAndExplode(centerX, centerY) {
if (this.animating) return;
this.animating = true;
// 1. 切割線動畫
this.lineX.style.top = centerY + "px";
this.lineY.style.left = centerX + "px";
this.lineX.style.transform = "scaleY(1)";
this.lineY.style.transform = "scaleX(1)";
await this.sleep(400);
// 2. 碎片爆炸動畫
await this.explodePieces(centerX, centerY);
// 3. 重組 (可選)
// await this.reassemble();
this.animating = false;
}
async explodePieces(cx, cy) {
const promises = this.pieces.map((piece, i) => {
return new Promise(resolve => {
setTimeout(() => {
// 計算從中心點發散的向量
const dx = piece.origX + piece.el.offsetWidth/2 - cx;
const dy = piece.origY + piece.el.offsetHeight/2 - cy;
const dist = Math.sqrt(dx*dx + dy*dy) || 1;
const force = 300 + Math.random() * 200; // 飛散距離
piece.tx = (dx / dist) * force;
piece.ty = (dy / dist) * force;
piece.rot = (Math.random() - 0.5) * 2; // -1 到 1 rad
piece.scale = 0.8 + Math.random() * 0.4;
piece.opacity = 0;
// CSS 過渡動畫
piece.el.style.transition = "transform 0.8s cubic-bezier(0.4,0,0.2,1), opacity 0.6s ease";
piece.el.style.transform = `translate(${piece.tx}px, ${piece.ty}px) rotate(${piece.rot}rad) scale(${piece.scale})`;
piece.el.style.opacity = "0";
setTimeout(resolve, 1000);
}, piece.delay);
});
});
await Promise.all(promises);
}
sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
}
// 使用
const slicer = new ImageSlicer(document.getElementById("stage"), "photo.jpg", 6, 4);
document.getElementById("stage").addEventListener("click", (e) => {
const rect = e.target.getBoundingClientRect();
slicer.sliceAndExplode(e.clientX - rect.left, e.clientY - rect.top);
});
.slice-piece {
backface-visibility: hidden; /* 修正 3D 翻轉閃爍 */
}
.slice-piece canvas { display: block; width: 100%; height: 100%; }
async function shuffleAndSolve() {
// 1. 打亂順序
const shuffled = [...pieces].sort(() => Math.random() - 0.5);
shuffled.forEach((p, i) => {
const col = i % cols, row = Math.floor(i / cols);
p.targetX = col * pieceW;
p.targetY = row * pieceH;
animateTo(p, p.targetX, p.targetY, 0, 1);
});
await sleep(800);
// 2. 用戶拖拽還原 (需實作拖拽邏輯)
// 3. 檢查完成 → 觸發慶祝動畫
}
background-position 重繪開銷requestAnimationFrame 而非 CSS transitioncanvas.width = canvas.height = 0大規模切片 (如 50×50=2500 片) 時,DOM+Canvas 達極限。改用 WebGL:
// 頂點著色器
attribute vec2 a_position; // 碎片在原圖的 UV
attribute vec2 a_offset; // 碎片目標偏移
uniform float u_progress; // 0~1 動畫進度
varying vec2 v_uv;
void main() {
v_uv = a_position;
vec2 target = a_position + a_offset * u_progress;
gl_Position = vec4(target * 2.0 - 1.0, 0, 1);
}
// 片段著色器
precision mediump float;
uniform sampler2D u_image;
varying vec2 v_uv;
void main() {
gl_FragColor = texture2D(u_image, v_uv);
}
圖片切割特效核心在於Canvas 切片離屏渲染 + CSS Transform 動畫。關鍵技術點:drawImage 九參數版本切片、transform-origin: center 確保旋轉中心正確、will-change 開啟 GPU 加速、錯開延遲產生波浪感。此技術可延伸至拼圖遊戲、圖片轉場、數據視覺化碎片化等場景。