HTML5 Canvas: Drawing an image with drawImage

This entry is part 15 of 17 in the series HTML5 Canvas

One of the more interesting areas of the Canvas API is the inclusion of images.

With the drawImage method, you can include an image of your choosing and manipulate the image in multiple ways.

<!DOCTYPE html>
<html lang='en'>
    <meta charset='utf-8'>
    <title> Text in canvas</title>
        canvas {
            border: 1px solid #000;
<canvas id='canvas' width='400' height='300'></canvas>
    var canvas = document.getElementById('canvas').getContext('2d');
    var canvasImage = new Image();
    function drawCanvasImage() {
        canvas.drawImage(canvasImage, 50, 50);
    canvasImage.addEventListener('load', drawCanvasImage, false);
    canvasImage.src = '';

The drawImage function has three different formats:

  • drawImage(image, x, y): Displays an image provided in the image URL at the location x and y
  • drawImage(image, x, y, w, h): Scales the image based on the display width (dw) and display height (h)
  • drawImage(image, sx, sy, sw, sh, x, y, w, h): Crops a section of the image based on the X,Y coordinate and width and height provided by (sx, sy, sw, and sh)


Series Navigation<< HTML5 Canvas: Filling up outline text
HTML5 Canvas: Cropping an image >>

Leave a comment

Leave a Reply