HTML5 Game - Canvas Drawing Images

Introduction

We can draw images on the canvas by using the drawImage method.

This method takes three, five, or nine arguments.

The first argument is the source of the image, which can be the DOM object that represents an img, video, or another canvas element.

When using three arguments, the second and third arguments give the coordinate on the canvas to paint the image.

The image is drawn at its intrinsic width and height.

When using five arguments, the additional arguments specify the width and height at which the image should be drawn.

It will override the intrinsic size.

For the nine arguments:

  • The second and third arguments are the offset into the source image.
  • The fourth and fifth arguments are the width and height of the region of the source image that will be used.
  • The sixth and seventh arguments specify the canvas coordinate at which the top-left corner of the selected region will be drawn.
  • The eighth and ninth arguments specify the width and height to which the selected region will be draw.

Drawing Images

You can draw existing image files on a canvas.

The drawing context offers the drawImage() method, which allows you to draw images on a canvas.

The following code shows the simplest form of using drawImage().

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
   <script src="https://code.jquery.com/jquery-2.1.3.js"></script> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){//from w w w .  j a  v a 2 s.  co  m
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
       let img = new Image(); 
       $(img).load(function () { 
         context.drawImage(img, 10, 20); 
       }); 
       img.src = "http://java2s.com/style/download.png"; 
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

This code creates an image using JavaScript code.

The jQuery code adds an event handler for the load event of the image object.

The load event is raised when an image is fully loaded.

Unless an image is fully loaded, you can't draw it on a canvas.

We call the drawImage() method inside the load event handler.

drawImage() accepts the image object and x and y coordinates where the image is to be drawn.

Related Topic