Course contentsShow
← Web Development
Lesson 2624 of 2,98247. Data VisualizationFree lesson

Drawing Images

Loading and rendering images on canvas with drawImage, including scaling and clipping.

Drawing Images

You'll learn how to load external images onto the canvas and control their size and visible area.

Now that you can draw shapes and text, the canvas can also display photographs, icons, and other external graphics. The drawImage() method brings image files into your canvas visualization, which is essential for adding logos, backgrounds, or photo-based data points to charts.

Loading an Image

Before drawing, you must load the image into an Image object:

const img = new Image();
img.src = 'chart-icon.png';

img.onload = function() {
  // Image is ready, safe to draw
  ctx.drawImage(img, 50, 50);
};

Never draw immediately after setting src — images load asynchronously. Always use the onload callback.

Three Signatures of drawImage()

Basic placement (original size):

ctx.drawImage(img, x, y);

Scaled rendering (resize the entire image):

ctx.drawImage(img, x, y, width, height);

Clipping and scaling (grab a section of the source image):

ctx.drawImage(img, 
  sourceX, sourceY, sourceWidth, sourceHeight,  // crop rectangle
  destX, destY, destWidth, destHeight);         // where/how to draw it

The nine-argument version acts like a photo cropper — you select a rectangular region from the source image and then specify where and how large to render that selection on the canvas.

Practical Example

const logo = new Image();
logo.src = 'company-logo.png';

logo.onload = function() {
  // Draw scaled logo in top-left corner
  ctx.drawImage(logo, 10, 10, 100, 50);
};

Key Takeaway: Use drawImage() to render external images on canvas; always wait for onload before drawing, and leverage the multi-argument signatures for scaling and cropping images directly during rendering.