Creating Maps Using Canvas or SVG

This topic compares how to use Canvas and SVG to create interactive maps that can be displayed on a webpage.

  • Canvas Code Sample
  • Canvas Code Sample Discussion
  • Drawing the Map
  • Processing the Click Event
  • SVG Code Sample
  • SVG Code Sample Discussion
  • Drawing the Map
  • Processing the Click Event
  • Comparison Summary
  • Related topics

This topic contains two stand-alone annotated code samples that demonstrate the different ways Canvas and SVG develop map images. These code samples are written in HTML5 and JavaScript. They explain the basic principles of how to create an interactive map for a webpage and process events when the map is clicked. Both samples show you how to: draw an outline map of Lake Michigan using x, y coordinates, and set up a function to respond to a click by displaying a message and changing the color of the map. The first code sample explains how Canvas creates the map components by using pixels in immediate mode. The SVG code sample that follows demonstrates how SVG creates the same components by using retained mode shape-based graphic techniques. The technical discussion after each sample explains how the code works and provides links to further information. The final comparison material summarizes the main differences of developing a map in each technology.

Canvas Code Sample

<!DOCTYPE html>
<html>
  
  <head>
    <script type="text/javascript">
      // Global variables
      var canvas;
      var ctx;

      // This function is called when the page loads.


      function init() {

        // Initialize canvas and get context.
        canvas = document.getElementById("canvas");
        ctx = canvas.getContext("2d");

        // Draw on the context.
        draw(ctx);
      }

      function draw(ctx) {

        // Draw on the canvas.
        // Get the drawing coordinates.
        makeLake();

        // Then fill and stroke the shape.
        // The fill is white.
        ctx.fillStyle = "white";
        ctx.fill();

        // The stroke is blue.
        ctx.strokeStyle = "blue";
        ctx.stroke();
      }

      function paintLake() {

        // If the shape is clicked, display a fact
        // and paint the lake.
        // Display a fact.
        alert("Lake Michigan is one of the five Great Lakes of America.");

        // Fill the lake with blue.
        ctx.fillStyle = "blue";
        ctx.fill();
      }

      function makeLake() {

        // These methods draw the shape of the lake.
        ctx.beginPath();
        ctx.moveTo(263.3, 11.3);
        ctx.lineTo(252, 28);
        ctx.lineTo(217.3, 28);
        ctx.lineTo(184, 74);
        ctx.lineTo(154, 123.3);
        ctx.lineTo(142, 170);
        ctx.lineTo(127.3, 214);
        ctx.lineTo(112.7, 252);
        ctx.lineTo(124, 284.7);
        ctx.lineTo(120, 318.7);
        ctx.lineTo(124, 356);
        ctx.lineTo(154, 389.3);
        ctx.lineTo(196.5, 356.7);
        ctx.lineTo(218.7, 318);
        ctx.lineTo(206, 240);
        ctx.lineTo(212.7, 182);
        ctx.lineTo(230.7, 121.3);
        ctx.lineTo(253.3, 103.3);
        ctx.lineTo(288, 74);
        ctx.lineTo(288, 23.3);
        ctx.closePath();
      }
    </script>
  </head>
  
  <body onload="init()">
    <h1>
      Lake Michigan
    </h1>
    <canvas id="canvas" width="400" height="400" onclick="paintLake()">
    </canvas>
    <p>
      Click on the lake to learn a fact about Lake Michigan.
    </p>
  </body>

</html>

Canvas Code Sample Discussion

This Canvas code sample uses a standard HTML5 header: <!doctype html>, so that browsers can distinguish it as part of the HTML5 specification.

The <canvas> tag is included in the body. You must specify the width and height. An ID is assigned to the tag so that it can be part of the document object model. You must also specify which function is called when the canvas is clicked.

The <script> portion of the page has two sections; one for drawing the map and the other for processing the click event on the map.

Drawing the Map

Canvas uses pixels in immediate mode to create the map images. When you begin to draw the map outline of Lake Michigan, the init function is called when the page loads. It draws the map in two steps.

The first step adds the canvas element to the document object model and initializes the drawing context. Then the draw function is called.

The second step is to draw the outline of Lake Michigan on the canvas. This is done by starting at one point and drawing lines to the other points that are defined by a set of x, y coordinates. The makeLake function is called to create a path consisting of moveTo and lineTo methods that outline the lake shape. Then the shape is filled with white and the edge is stroked with blue.

For this sample, Adobe Illustrator CS5 was used to calculate the coordinates. This makes it easy to transfer map shapes to a form that can be used by Canvas. To use this technique, you must load the AI2Canvas plug-in, available from https://visitmix.com/labs/ai2canvas/.

. First a satellite map of Lake Michigan was loaded into Illustrator, and a new layer was created on top of it. Then the lake was traced by hand. The layer was then exported (without the satellite map) using AI2Canvas to an HTML page. From that HTML document, the data was copied and pasted to this example's makeLake function.

Processing the Click Event

The paintLake function is called when the user clicks the canvas element. An alert box is displayed and the canvas shape is filled with blue. Be aware that this assumes that the last shape created by using closePath has not changed. Each time you create a new path, the old path is no longer the current path. fill and stroke only apply to the current path.

SVG Code Sample

<!DOCTYPE HTML>
<html>
  
  <head>
    <script type="text/javascript">
      // This function is called when the lake is clicked.


      function lakeColor() {

        // Display a fact.
        alert("Lake Michigan is one of the five Great Lakes of America.");

        // Get the SVG polygon element.
        var myLake = document.getElementById("lake");

        // Color it by changing the fill attribute.
        myLake.setAttribute("fill", "blue");
      }
    </script>
  </head>
  
  <body>
    <h1>
      Lake Michigan
    </h1>
    <!-- Create the main SVG element. -->
    <svg x="0" y="0" width="400" height="400">
      <!-- Add the polygon element. -->
      <polygon fill="white" stroke="blue" id="lake" onclick="lakeColor()" points="263.3,11.3 252,28 217.3,28 184,74 154,123.3 142,170 
      127.3,214 112.7,252 124,284.7 120,318.7 124,356 154,389.3 196.5,356.7 218.7,318 206,240 212.7,182 230.7,121.3 253.3,103.3 
      288,74 288,23.3 " />
    </svg>
    <p>
      Click on the lake to learn a fact about Lake Michigan.
    </p>
  </body>

</html>

SVG Code Sample Discussion

This SVG code sample uses a standard HTML5 header: <!doctype html>, so that browsers can distinguish it as part of the HTML5 specification. Be aware that not all browsers support this aspect of HTML5, where SVG tags are treated as if they are HTML tags. This treatment is called inline SVG.

Drawing the Map

SVG uses retained mode to create the shape-based map outline. You begin doing this by putting an svg tag in the webpage body. You must also specify the width and height of the SVG drawing container. Then a polygon is embedded inside the SVG container. The polygon has a white fill, a blue stroke, and an ID of lake so it can be included in the document object model. The polygon’s onclick attribute must specify the lakeColor function as the target if the element is clicked. Unlike the Canvas sample, with SVG you can respond to click events on each separate element. A click outside the polygon is not processed

In this sample, Adobe Illustrator CS5 was used to calculate the coordinates for the polygon. First a satellite map of Lake Michigan was loaded into Illustrator and a new layer was created on top of it. Then the lake was traced by hand. The layer was saved as a SVG document. From the SVG document, it was easy to copy and paste the sequence of coordinate to this example's polygon element..

Processing the Click Event

The script section has one function which processes the click event when you click on the lake. The lakeColor function displays an alert message when the lake shape is clicked. It also colors the lake “blue” by changing the polygon attribute.

Comparison Summary

The main difference between the two code samples discussed here is the way they create images and put them on the screen. SVG’s retained mode graphic display system allows you to create all the map details in HTML-like tags in the body and modify them in script by changing shape attributes. Canvas requires more code to accomplish the same task, because the shapes must be drawn in script and the body only contains the basic Canvas tag. In this example, the fill is done by using the fillStyle method, but if an intermediate shape had been used, the lake shape would have to be redrawn. Also, because Canvas uses immediate mode, the shape cannot be modified as easily as an SVG shape.

In general, SVG can create maps using fewer lines than Canvas. In the code samples used for this comparison, the SVG map code has 40 lines and the Canvas map code has 91 lines. Both technologies are supported by Adobe Illustrator CS5, allowing you to create your map in Illustrator and then copy the data directly into your HTML code.

How to Choose Between Canvas and SVG to Create Web Graphics