Canvas API 的 drawImage() 方法可將 ``、`
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="400" height="300" style="border:1px solid #ccc">
瀏覽器不支援 Canvas
</canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {
// 基本繪製:左上角 (0,0) 原尺寸
ctx.drawImage(img, 0, 0);
// 進階:縮放繪製
// ctx.drawImage(img, 0, 0, 200, 150);
// 進階:裁切繪製 (來源區域 -> 目標區域)
// ctx.drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
};
img.src = 'https://example.com/flower.png'; // 跨域圖片需 CORS 標頭
</script>
</body>
</html>
| 簽名 | 用途 |
|---|---|
drawImage(img, x, y) | 原尺寸繪製於 (x,y) |
drawImage(img, x, y, w, h) | 縮放繪製 |
drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) | 裁切來源區域並縮放至目標區域 |
掌握 `drawImage()` 三種重載與 `onload` 非同步流程,即可實現圖片合成、裁切、縮放、濾鏡等豐富 Canvas 應用。