Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

วิธีวาดรูปภาพด้วย drawImage() ใน HTML5 Canvas

เมธอด drawImage() ของ Canvas 2D Context ใช้วาดรูปภาพ, canvas อื่น, หรือ video frame ลงบน canvas สามารถ crop, scale, transform ได้

Syntax Variations

// Basic - วาดเต็มรูป
ctx.drawImage(image, x, y)

// With scaling - วาดพร้อม resize
ctx.drawImage(image, x, y, width, height)

// With cropping - crop แล้ววาด
ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

Parameter

Parameterคำอธิบาย
imageHTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap
sx, sySource x, y (มุมซ้ายบนของพื้นที่ crop)
sWidth, sHeightSource width, height (ขนาดพื้นที่ crop)
dx, dyDestination x, y (ตำแหน่งบน canvas)
dWidth, dHeightDestination width, height (ขนาดที่วาดบน canvas)

ตัวอย่าง: วาดรูปพื้นฐาน

<canvas id="canvas" width="400" height="300"></canvas>
<script>
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');
  const img = new Image();
  img.onload = () => {
    ctx.drawImage(img, 50, 50, 200, 150); // x, y, width, height
  };
  img.src = 'image.jpg';
</script>

ตัวอย่าง: Sprite Sheet (Crop Animation)

const spriteWidth = 64, spriteHeight = 64;
let frame = 0;

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  const sx = (frame % 4) * spriteWidth;
  const sy = Math.floor(frame / 4) * spriteHeight;
  ctx.drawImage(spriteSheet, sx, sy, spriteWidth, spriteHeight, 100, 100, 128, 128);
  frame = (frame + 1) % 8;
  requestAnimationFrame(animate);
}

ข้อควรระวัง

  • รอ image.onload ก่อน draw (async)
  • Cross-origin images ทำให้ canvas "tainted" (ไม่ได้ read pixels) - ใช้ crossorigin="anonymous" + CORS header
  • Image ต้องโหลดเสร็จแล้ว纔 draw ได้