Over a million developers have joined DZone.

Exploring HTML5 Canvas: Part 1 - Introduction

DZone's Guide to

Exploring HTML5 Canvas: Part 1 - Introduction

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

In this post, I'm going to begin an examination of one of the hottest new features of HTML5, namely the Canvas element.

What is Canvas, anyway?

The best place to start is at the beginning, and that's with an explanation of what Canvas actually is. Canvas is a new element that is part of the HTML5 specification, and can be added to your markup as simply as this:

<canvas id="myCanvas" width="500" height="500"></canvas>

OK, we're done. Let's go home.

Of course, it's not that easy. By adding the canvas element to the markup, if we browse the page containing the element in a modern browser that supports canvas (you can find out which browsers support canvas using caniuse.com), you'll see a great big nothing. Why? Because all that the <canvas> tag gives you is a blank slate, and unless you've changed the background color of your page, both the page background and the canvas will be white. Not terribly interesting to look at, so I'll spare you the screen shot of the blank canvas. Just take my word that the above markup gives you a drawing surface that is 500 pixels wide by 500 pixels tall, and (assuming it's the only element in the body of your page) will appear at the top left of your page.

Building a Template

To make life easier as we explore the HTML5 Canvas, I'm going to start with a basic set of markup and script, and in future posts in this series, I'll add to that basic template. Since this will consist solely of HTML markup, CSS, and Javascript, you can use any text editor you like to follow along. I'll be working with the Microsoft WebMatrix 2 beta, which you can download here (you can choose either the current v1 release, or the v2 beta, using the big green buttons in the upper right).

Here's the basic template I'm going to use:

  <!DOCTYPE html>
 <html lang="en">
         <meta charset="utf-8" />
         <title>HTML5 Canvas Template</title>
             /* styles here */
          <canvas id="myCanvas" width="500" height="500">
              <p>Canvas not supported.</p>
          <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" type="text/javascript"></script>
          <script type="text/javascript">
              $(document).ready(function() {
                  var canvas = $("#myCanvas").get(0);
                  var context = canvas.getContext("2d");
                  function renderContent()
                      // we'll do our drawing here...

Some things to note:

  • On line 7, I'm setting up a <style> block where we'll put CSS rules.
  • On line 13, I've added some content in between the <canvas> and </canvas> tags. Any browser that does not support Canvas will ignore the canvas tags, and will instead render the content within them. In this case, I'm simply displaying a message, but I could also provide a fallback solution using Silverlight or Flash, if I chose.
  • On line 16, I'm importing the jQuery script library, which can help simplify and speed my Javascript development. I am placing my script references at the end of the page, just prior to the closing </body> element tag, to ensure that my page content loads without being blocked by script loading.
  • On line 18, I am telling jQuery to execute an anonymous function when the page is ready for scripting, using jQuery's built-in ready event. This is where I kick off processing, first getting a reference to the canvas element and its 2d drawing context (more on this in a bit), and calling the renderContent function, which is currently empty.
  • A final note…in a production site, I would separate out the CSS and JavaScript into separate files, to keep my markup nice and clean. For the sake of this blog series, I will largely keep the CSS and JavaScript in the same file, so you'll be able to see it all at once.

All of the parts of this template will be useful moving forward, so you may want to copy the above code and save it to a file. I'm calling mine CanvasTemplate.html:


A Brief Digression – JsFiddle

Another useful tool I want to introduce, since I'll probably use it from time to time to post example code, is JsFiddle. JsFiddle is, as the JsFiddle docs state,"a playground for web developers, a tool which may be used in many ways." It supports multiple JavaScript libraries, such as jQuery, MooTools, Prototype, and many more, and makes it easy to experiment with, and share, your web code. You can see an example in the code snippet I posted for making a grid in canvas as an aid to visualizing layout:

It's important to note that JsFiddle is an alpha release as of this writing, and I've found a few issues when editing scripts, particularly when using tabs. But overall, it's very functional, and quite convenient for brief forays into web monkeying. For deeper development, I definitely prefer an environment like WebMatrix or Visual Studio that provide a more robust editing experience.

A Blank Slate

Back to the code…as noted above, even with the addition of our JavaScript in the template, our canvas still isn't doing anything useful. In order to start drawing, we need the canvas equivalent of a pencil (or pen, or paintbrush, depending on which metaphor you prefer). And that's where the Context comes in. The HTML5 Canvas element exposes a function called getContext, which you can call like so:

var context = myCanvasElement.getContext("2d");

Note that in the snippet above, I've already gotten a reference to the canvas element (you'll see how momentarily), and I'm passing in the string argument "2d" to the function. This is required, although in the current specification, there is only one drawing context, which is 2d (there may be a 3d context in future versions of the specification, which is why you have to specify 2d, even though it's the only context). It is this context that exposes all of the functions you'll call to draw on your canvas.

Getting the drawing context takes just 2 lines, one to get a reference to the canvas element you want to draw on, and another to get the context itself. We'll use jQuery to grab the element, using its ID selector syntax:

var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");

In the first line, I ask jQuery for the element with the id of "myCanvas" and call .get(0) to get the underlying element (by default, jQuery returns a set of elements wrapped with some of its useful functionality…but we just need the element itself), then in the second line I grab the canvas drawing context and stick it into a variable called, appropriately enough, "context". In our template above, I define and populate these variables at the beginning of the anonymous function called by jQuery's ready event handler. Since the renderContent function is also defined within the anonymous function, it will have access to the canvas and context variables, while keeping both the variables and function from polluting the global namespace (that is, unintentionally exposing variables and/or functions as global to the page).

We'll get into the ins and outs of the canvas drawing API in the next installment, but I'll leave you with a simple example of what you can do with Canvas, by adding the following code to the renderContent function:

  function renderContent()
      context.fillRect(0, 0, canvas.width, canvas.height);
      var text = "Hello, Canvas!";
      context.fillStyle = "#FF0000";
      context.strokeStyle = "#0000FF";
      context.font = "36px sans-serif";
      context.strokeText(text, 10, 50);
      context.fillText(text, 10, 50);

Which results in the following being rendered:


Hope you enjoyed the first installment of Exploring HTML5 Canvas.

If you found this useful, why not tell your friends? You can also subscribe to my RSS feed, and follow me on twitter for more frequent updates.

More parts in the series:




Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.


Published at DZone with permission of G. Andrew Duthie, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}