Quantcast
Viewing latest article 4
Browse Latest Browse All 11

Exploring HTML5 Canvas: Part 1 – Introduction

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:

   1: <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:

   1:  <!DOCTYPE html>
   2:   
   3:  <html lang="en">
   4:      <head>
   5:          <meta charset="utf-8" />
   6:          <title>HTML5 Canvas Template</title>
   7:          <style>
   8:              /* styles here */
   9:          </style>
  10:      </head>
  11:      <body>
  12:          <canvas id="myCanvas" width="500" height="500">
  13:              <p>Canvas not supported.</p>
  14:          </canvas>
  15:          
  16:          <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" type="text/javascript"></script>
  17:          <script type="text/javascript">
  18:              $(document).ready(function() {
  19:                  var canvas = $("#myCanvas").get(0);
  20:                  var context = canvas.getContext("2d");
  21:   
  22:                  function renderContent()
  23:                  {
  24:                      // we'll do our drawing here...
  25:                  }
  26:   
  27:                  renderContent();
  28:              });
  29:          </script>
  30:      </body>
  31:  </html>

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:

Image may be NSFW.
Clik here to view.
image_2

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:

   1:  function renderContent()
   2:  {
   3:      context.fillRect(0, 0, canvas.width, canvas.height);
   4:   
   5:      var text = "Hello, Canvas!";
   6:      context.fillStyle = "#FF0000";
   7:      context.strokeStyle = "#0000FF";
   8:      context.font = "36px sans-serif";
   9:      context.strokeText(text, 10, 50);
  10:      context.fillText(text, 10, 50);
  11:  }

Which results in the following being rendered:

Image may be NSFW.
Clik here to view.
image_4

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:

The post Exploring HTML5 Canvas: Part 1 – Introduction appeared first on Devhammer Enterprises.


Viewing latest article 4
Browse Latest Browse All 11

Trending Articles