SyntaxStudy
Sign Up
HTML Drawing Images on Canvas
HTML Intermediate 5 min read

Drawing Images on Canvas

Images on Canvas

drawImage() renders an image element, video frame, or another canvas onto the canvas. The image must be fully loaded before drawing.

Example
const img = new Image();
img.src = "photo.jpg";
img.onload = () => {
  const ctx = canvas.getContext("2d");

  // Draw at position (0,0)
  ctx.drawImage(img, 0, 0);

  // Draw scaled to 300x200
  ctx.drawImage(img, 0, 0, 300, 200);

  // Draw cropped: source(sx,sy,sw,sh) dest(dx,dy,dw,dh)
  ctx.drawImage(img, 100, 100, 200, 200, 0, 0, 150, 150);
};
Pro Tip

Always draw inside the image's onload callback — drawing before load results in a blank or broken image.