const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = 'cat.jpg';
// ❌ 錯誤寫法:圖片未加載完成即繪製,首次載入常顯示空白
// ctx.drawImage(img, 10, 10, 490, 382);
// ✅ 正確寫法:監聽 onload 事件
img.onload = () => {
ctx.drawImage(img, 10, 10, 490, 382);
};
// 處理加載失敗
img.onerror = () => {
console.error('圖片加載失敗:', img.src);
};

new Image() 發起的網絡請求是**異步**的。當 drawImage() 執行時,若圖片數據尚未下載完成,Canvas 繪製的是「空白」幀。瀏覽器緩存生效後(刷新頁面),圖片從內存/磁盤緩存即時可用,故第二次能正常顯示。
// 1. 基礎繪製(原始尺寸)
ctx.drawImage(image, dx, dy);
// 2. 指定目標寬高(拉伸/縮放)
ctx.drawImage(image, dx, dy, dWidth, dHeight);
// 3. 切片繪製(精靈圖/裁剪)
ctx.drawImage(image,
sx, sy, sWidth, sHeight, // 源圖矩形
dx, dy, dWidth, dHeight // 目標矩形
);
參數說明:
• sx, sy:源圖裁剪起點座標;
• sWidth, sHeight:源圖裁剪寬高;
• dx, dy:Canvas 目標繪製起點;
• dWidth, dHeight:Canvas 目標繪製寬高。
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
}
// 使用
(async () => {
const [bg, avatar] = await Promise.all([
loadImage('bg.jpg'),
loadImage('avatar.png')
]);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
ctx.drawImage(avatar, 100, 100, 200, 200);
})();
crossOrigin若圖片來自不同域且需讀取像素數據(getImageData、toDataURL),必須設置:
img.crossOrigin = 'Anonymous'; // 或 'use-credentials'
img.src = 'https://cdn.example.com/image.jpg';
且服務端需返回 Access-Control-Allow-Origin: *(或指定域)。
drawImage 到主 Canvas;requestAnimationFrame 幀同步動畫繪製。掌握異步加載機制,是 Canvas 圖片繪製的「第一道坎」。記住:**永遠在 onload 回調中繪製**,或使用 Promise 封裝實現鏈式調用,徹底告別首屏空白問題。