Reuse and Recycle: The Canvas 2D API

The canvas element and associated API started life as an Apple extension to HTML. From there it blossomed into one of the early stars of the HTML5 era. The canvas element provides a scriptable interface for drawing two-dimensional images in the browser. Even without full browser support on the desktop, developers have embraced canvas fully. It’s been used for everything from high traffic visualizations to game engines, a popular system for delivering custom fonts, and a port of the Processing programming language into JavaScript.

While the true power of the Canvas 2d API is beyond the scope of this higher level introduction, it’s worth looking at the API in brief, if just to get a flavor for what it looks like. The following code sample shows a small canvas element and associated JavaScript that draws out a tic-tac-toe game. The simplest piece is the canvas element itself. A canvas element operates much like any other replaced element like a video tag or an image. The big difference is that it lacks a src attribute. The “src” of the canvas image is provided by JavaScript.

<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="_assets/css/style.css">
</head>
<body>
<header>
  <h1>Mobile Web App Cookbook, Canvas</h1>
</header>
<canvas id="ctx" height="300" width="300"></canvas>
<footer>
  <p>&copy; <a href="https://htmlcssjs.wpengine.com/" rel="me">Rob Larsen</a></p>
</footer>
<script src="_assets/js/libs/jquery-1.7.1.min.js"></script>
<script>
//canvas script follows below
</script>

</body>
</html>

The Canvas API is illustrated the in the following script block. It starts by getting a reference to the context of the canvas element. The context is where information about the current rendering state of the element is stored. It contains both the pixel level state of the image as well as various properties and access to core canvas methods used to further manipulate the image. After that you’ll see a variety of basic drawing commends. A path is created using the ctx.beginPath() method and then several context level styles are set. Following that a simple for loop is used to draw lines at regular intervals on the screen. The combination of moving the insertion x/y point of the drawing using ctx.moveTo and drawing the actual line using ctx.lineTo is enough to illustrate the familiar tic-tac-toe board. Following that the “game” is played using a series of text insertions, alternating different fillStyle colors between “turns.”

$( document ).ready(function(){
  var ctx = document.getElementById( "ctx" ).getContext( "2d" ),
  width =  document.getElementById( "ctx" ).width;
  //draw the board
  ctx.beginPath();
  ctx.strokeStyle = '#000';
  ctx.lineWidth = 4;
  for ( var i=1; i < 3; i++ ){   
    ctx.moveTo( ( width / 3 ) * i, 0 );
    ctx.lineTo( ( width / 3 ) * i , width );
    ctx.moveTo( 0, ( width / 3 ) * i );
    ctx.lineTo( width, ( width / 3 ) * i );
  }
  ctx.stroke();
  ctx.closePath(); 
  //"play" the game in order
  ctx.font="80px Arial, Helvetica, sans-serif";
  ctx.fillStyle="#c00";
  ctx.fillText( "x", 130, 170 );
  ctx.fillStyle="#000";
  ctx.fillText( "0", 30, 70 );
  ctx.fillStyle="#c00";
  ctx.fillText( "x", 30, 170 );
  ctx.fillStyle="#000";  
  ctx.fillText( "0", 230, 170 )
  ctx.fillStyle="#c00";;
  ctx.fillText( "x", 130, 70 );
  ctx.fillStyle="#000";  
  ctx.fillText( "0", 130, 270 );
  ctx.fillStyle="#c00";
  ctx.fillText("x", 230, 70 );
  ctx.fillStyle="#000";  
  ctx.fillText( "0", 30, 270 )
  ctx.fillStyle="#c00";;
  ctx.fillText( "x", 230, 270 );
});

This is a simplistic example but it should illustrate the flavor of the API and, hopefully, will get you excited to use some more advanced features.

2 thoughts on “Reuse and Recycle: The Canvas 2D API

  1. 1) You’re missing a ” on line 3 of your second code block. You’ve also got a second ; on line 34

    2) You have this wrapped in a jQuery ready function, however none of the code is jQuery.

  2. 1) Thanks. Syntax highlighting to the rescue.
    2) True. I could have wrapped it in document.addEventListener("DOMContentLoaded", etc) and didn’t. I didn’t really think about it. For better or worse, wrapping this in a jQuery ready function is going to be clearer to people who are going to get something out of a basic introduction to the canvas element.

Leave a Reply

Your email address will not be published. Required fields are marked *