Home > Articles > Web Development > HTML/CSS

  • Print
  • + Share This
From the author of Images on a Canvas

Images on a Canvas

Working with images is just as easy. The canvas API drawImage method places an image at a specific location on a canvas with optional scaling factors. The following code example places a United States flag on a world map wherever you click the mouse. Both the map and the flag are from the CIA's World Fact Book. Feel free to choose your own flag or icon to conquer the world. (Note: The image URLs do not contain any blanks.)

<!DOCTYPE html>
<head><title>Canvas Image Example</title>
<script type="text/javascript">

// load images into the cache
var map_image = new Image();        // load the map image
map_image.src = 'https://www.cia.gov/library/publications/the-world-factbook/

var flag_image = new Image();        // load the flag image
flag_image.src = 'https://www.cia.gov/library/publications/the-world-factbook/

// initialize the drawing area, called by body onload
function initCanvas(c) {
  canvas = document.getElementById(c);
  ctx = canvas.getContext("2d");
  ctx.drawImage(map_image, 0, 0);

  // set a click handler on the canvas
  canvas.onclick = function (e) {
    var x = e.clientX - 24;        // offset to center of flag
    var y = e.clientY - 12;
    ctx.drawImage(flag_image, x, y, 48, 25);

<!-- initialize the canvas after the body loads -->
<body onload="initCanvas('c2');" style="margin:0;"> 

<!-- Canvas element for map --> 
<canvas id="c2" width="700" height="380">No Canvas</canvas>

In this example, the JavaScript is in the document head. First, the two images, map_image and flag_image, are created. Setting their src properties loads the images into the browser's cache, making them available to the canvas API when the page loads.

Second, an initCanvas function is defined that will establish the canvas 2D drawing context and draw the map at location (0,0) —the top-left corner of the canvas (x and y values increase to the right and down, respectively.)

The initCanvas function also defines a event handler that will be called whenever the user clicks on the canvas. The handler function is passed an event object from which it gets the x and y window coordinates of the click. It draws the flag scaled to 48x25 pixels, offset to place the flag's center at the click point.

Figure 2 shows what the canvas looks like after I've clicked the canvas a number of times to plant the flag. A working demo is also available.

Figure 2 Map and flags—working with images on the HTML5 canvas.

These examples demonstrate how easy it is to build useful web applications on the canvas. In the map and flag example, only a few more lines of code would allow the user to pick her own flag or pop up information related to the clicked location. A few other points are worth noting about this example:

  • Anything drawn on the canvas becomes part of the canvas's bitmap. A flag, once it is drawn, ceases to exist as a separate image object. It can't be moved around or erased without redrawing the entire map each time before drawing the flag somewhere else, or not at all. Separate graphical objects that can be moved, scaled, erased, and otherwise manipulated, are in the realm of Scalable Vector Graphics (SVG), another part of the HTML5 package that's not as well supported as the canvas element is now.
  • The canvas accommodates videos as easily as images. The drawImage method used in the example can be called with either an image or a video object. Both the map and the flag images can be replaced with running videos. Loading a video into a canvas element provides the ability to manipulate video frames at runtime. This is explored in a great blog post, “Blowing Up HTML5 Video and Mapping It into 3D Space,” by Sean Christmann.
  • Everything is out in the open. All of the source code—HTML, JavaScript and CSS—is available for copying and reuse by anyone with a browser. Canvas applications can be inspected, tested, and debugged using just the browser's built-in tools: the Element Inspector, JavaScript Console, and HTML Source Viewer. This is good news for developers, as it encourages feedback and promotes collaborative efforts.
  • Everything is out in the open! This is bad news for producers. It is difficult to protect the intellectual property value of a canvas application's code. Anyone can take a copy, rebuild, and deploy it for their own profit, leaving no recourse other than to sue after the fact. There are also source origin problems with the canvas where the bits and pieces of the content and code can reside on different servers in multiple Internet domains, providing opportunities for confusion and abuse.
  • + Share This
  • 🔖 Save To Your Account