CanvasRenderingContext2D.drawImage() 是 Canvas 繪製圖片/視訊/另一個 Canvas 的核心方法,提供三種重載滿足從簡單貼圖到複雜精靈圖切割的所有需求。本文系統整理三種簽名、參數含義、常見陷阱,並實作「九宮格縮放」與「精靈圖動畫」兩大實戰範例。
| 簽名 | 參數 | 用途 | 典型場景 |
|---|---|---|---|
drawImage(img, x, y) | 圖片、目標左上角座標 | 原尺寸繪製 | 背景圖、UI 圖示、截圖 |
drawImage(img, x, y, w, h) | + 目標寬高 | 縮放繪製 | 縮圖、自適應容器、按比例縮放 |
drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) | 源矩形 + 目標矩形 | 切割+縮放 | 精靈圖、圖集、九宮格、局部放大 |
參數命名慣例:s=source(源)、d=destination(目標)、x/y=座標、w=width、h=height。
onloadconst img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0); // 此處安全繪製
};
img.src = 'photo.jpg'; // 觸發載入
// 若圖片已快取,onload 可能同步觸發,仍建議統一用 onload 保護
保護四邊框線不變形,僅拉伸中間區域。適用於對話框、按鈕、面板背景。
function drawNinePatch(ctx, img, dx, dy, dw, dh, border) {
// border = {top, right, bottom, left} 邊框厚度(源圖像素)
const {top, right, bottom, left} = border;
const sw = img.width, sh = img.height;
// 定義 3x3 網格源座標
const sx = [0, left, sw-right];
const sy = [0, top, sh-bottom];
const swArr = [left, sw-left-right, right];
const shArr = [top, sh-top-bottom, bottom];
// 目標座標
const dxArr = [dx, dx+left, dx+dw-right];
const dyArr = [dy, dy+top, dh+dy-bottom];
const dwArr = [left, dw-left-right, right];
const dhArr = [top, dh-top-bottom, bottom];
for (let row=0; row<3; row++) {
for (let col=0; col<3; col++) {
// 跳過四角為 0 尺寸的情況
if (swArr[col]<=0 || shArr[row]<=0 || dwArr[col]<=0 || dhArr[row]<=0) continue;
ctx.drawImage(img,
sx[col], sy[row], swArr[col], shArr[row],
dxArr[col], dyArr[row], dwArr[col], dhArr[row]
);
}
}
}
// 使用:邊框 12px 的對話框背景
const bubble = new Image(); bubble.src = 'bubble9.png';
bubble.onload = () => drawNinePatch(ctx, bubble, 50, 50, 300, 150, {top:12,right:12,bottom:12,left:12});
const sprite = new Image(); sprite.src = 'run_sprite.png'; // 8 幀橫向排列,每幀 64x64
const FRAME_W = 64, FRAME_H = 64, TOTAL = 8;
let frame = 0, lastTime = 0;
function animate(time) {
if (time - lastTime > 100) { // 10 FPS
frame = (frame + 1) % TOTAL;
lastTime = time;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(sprite, frame*FRAME_W, 0, FRAME_W, FRAME_H, 100, 100, FRAME_W*2, FRAME_H*2); // 放大 2 倍顯示
requestAnimationFrame(animate);
}
sprite.onload = () => requestAnimationFrame(animate);
onload 後或 img.complete 為 true 時繪製。if(sx+sw>img.width||sy+sh>img.height) throw...。ctx.scale(-1,1) 配合 translate。drawImage(offscreenCanvas, ...),減少狀態切換。img.crossOrigin='anonymous' + 伺服器 CORS 標頭,否則後續 getImageData/toDataURL 會拋錯。ctx.globalAlpha/transform,改用 ctx.save()/restore() 包裹整組。createImageBitmap()(支援瀏覽器)預解碼圖片至 GPU 記憶體,繪製速度提升 2-5 倍。