Image

We can draw an existing image on Canvas.

Functions:

There are three drawImage functions:

image parameter is the image to draw.

dx and dy parameters are short for "destinationX" and "destinationY". These parameter determine where on the canvas the image is drawn.

dw and dh parameters are short for "destinationWidth" and "destinationHeight". These parameters determine the size to scale the image to when drawing it.

sx and sy parameters are short for "sourceX" and "sourceY". These parameters determine from where in the source image to start copying a rectangle of the image onto the canvas.

sw and sh parameters are short for "sourceWidth" and "sourceHeight" .

Image Loading:

The following code demonstrates how the image is loaded:

var image = new Image();
image.src = "images/my-image.jpg";

Before using the image we have be sure that it is already loaded. For example:

img.onload = function () {
   draw();
}

After that we can use canvas drwaImage functions.

function draw() {
    var canvas  = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.drawImage(image, 10, 10);
}

To Do

Try the following options:

  1. Use only half of the viewBox for the image
    ctx.drawImage( img, 0, 0, img.width, img.height,
            0, 0, 200, 200 );
  2. Same as previous, but with different start location of the image
    ctx.drawImage( img, 0, 0, img.width, img.height,
            100, 100, 200, 200 );
  3. Part of the image is used
           ctx.drawImage( img, 0, 500, img.width, img.height,
            0, 0, canvas.width, canvas.height );