9 min read

HTML5 Multimedia Development Cookbook

HTML5 Multimedia Development Cookbook

Recipes for practical, real-world HTML5 multimedia driven development.

The cool thing with the new open-source canvas element is that not only can you create dynamic images on the fly, but the users’ actions can create new images in real time as well—all without requiring a plugin. Sounds great, right? In many ways it is, but it also leaves our friends using assistive technologies out in the cold.

What will happen if you’re using a browser that doesn’t support the new canvas element? Pretty much nothing. The browser just won’t display it. That’s why you’ll need to be especially careful with this technology and not place anything inside the new canvas element on which your site or application absolutely depends. You must also consider fallback content.

Browsers that support canvas include:

HTML5 Multimedia Development Cookbook

Before proceeding with developing with the new canvas element, make sure you have a good foundation of skills with HTML and JavaScript. Being comfortable with object-oriented programming sure wouldn’t hurt either.

Now, let’s get cooking!

Setting up the canvas environment

Creating the new canvas element is easy.

How to do it…

Check out how simple this is:

<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset=”utf-8″ />
</head>
<body>
<canvas id=”FirstCanvas” width=”800″ height=”600″>
<!– Fallback code goes here –>
</canvas>
</body>
</html>


How it works…

Of course, we can use whatever height and width dimensions we need, but that simple set of tags is what we need to start.

You’re probably thinking we could use CSS to control the height and width, but resist that temptation. Because the new canvas element contains a 2d rendering context, that approach can cause unpredictable behavior.

There’s more…

Next, we’ll call the new canvas element JavaScript API while calling jQuery:

<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset=”utf-8″ />
<script
src=”http://ajax.googleapis.com/ajax/libs/jquery/1/
jquery.min.js”></script>
<script>
$(document).ready(function() {
var canvas = document.getElementById(“FirstCanvas”);
var ctx = canvas.getContext(“2d”);
});
</script>
</head>
<body>
<canvas id=”FirstCanvas” width=”800″ height=”600″>
<!– Fallback code goes here –>
</canvas>
</body>
</html>


He’s smart

“Let me make one thing completely clear: When you use canvas, you’re not drawing on the canvas element itself. Instead, you’re actually drawing on the 2d rendering context, which you’re accessing through the canvas element via the JavaScript API.” – Rob Hawkes

What am I sayin’?

Apple first introduced the new canvas element for the OSX Dashboard years ago. It was later implemented in web browsers Safari and then Chrome, with other browsers following suit. Since then it’s become an official part of the HTML5 specification.

What’s next for <canvas>?

Right now, we’re barely scratching the surface of what the new canvas element can do. Now and in the future we’ll use it to create animations, charts, diagrams, drawing apps, graphs, and user interfaces. What will you dream up?

See also

Developer Martin Angelov penned a great how-to guide titled, “An HTML5 Slideshow w/Canvas & jQuery” for Tutorial Zine at: http://tutorialzine.com/2010/09/html5-canvas-slideshow-jquery. In it, Martin demonstrates how to combine the new canvas element with jQuery, the most popular JavaScript framework, to create an intensely interactive image slideshow.

Understanding the 2d rendering context

It’s important to understand that the new canvas element is really a “surface” on which to draw bitmapped images in the browser.

How to do it…

Defining a canvas tag like this only tells half the story:

<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset=”utf-8″ />
</head>
<body>
<canvas id=”FirstCanvas” width=”800″ height=”600″>
<!– Fallback code goes here –>
</canvas>
</body>
</html>


How it works…

By itself that HTML5 code does nothing. We have to use JavaScript to make the Document Object Model retrieve the 2d rendering context in order to get something to happen:

<script>
   $(document).ready(function() {
   var canvas = document.getElementById("FirstCanvas");
   var ctx = canvas.getContext("2d");
   });
</script>

To be fair, that bit of JavaScript won’t do anything without the canvas tag in the HTML either.

There’s more…

You may be wondering about the name. If there’s a 2d rendering context, isn’t there probably a 3d rendering context too? The short answer is yes. But the more detailed answer isn’t so simple.

While a 3d rendering context does exist in theory, at the time of this publication no browser supports it. So if the new canvas element renders in 3d but nobody sees it, did it really do anything?

You can master <canvas>

The 2d context uses a number of different drawing contexts for the new canvas element that use syntaxes that should look quite familiar if you’re experienced with CSS and JavaScript.

X, meet Y

When drawing, remember the X and Y axis in the top left corner of your browser window. Values increase going down the page.

Respect my authority!

The World Wide Web Consortium’s HTML5 Canvas 2d Context specification is online at: http://dev.w3.org/html5/2dcontext. There we can dig even deeper into information like conformance requirements, the canvas state, transformations, compositing, colors and styles, line styles, shadows, simple shapes, complex shapes, focus management, text, images, pixel manipulation, drawing model, examples, and more.

Processing shapes dynamically

Let’s look at the JavaScript functions that allow the new canvas element to draw rectangles.

How to do it…

fillRect(x,y,width,height)
strokeRect(x,y,width,height)

In order:

fillRect(x,y,width,height)

draws a filled rectangle. Next,

strokeRect(x,y,width,height)

draws an outline around the rectangle.

Now, let’s draw some shapes.

How it works…

We’ll start with our basic canvas code and incorporate our new functions:

<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset=”utf-8″ />
<script
src=”http://ajax.googleapis.com/ajax/libs/jquery/1/
jquery.min.js”></script>
<script>
$(document).ready(function() {
var canvas = document.getElementById(“FirstCanvas”);
var ctx = canvas.getContext(“2d”);
ctx.strokeRect(10, 10, 396, 236);
ctx.fillStyle = “red”;
ctx.fillRect(11, 11, 100, 100);
ctx.fillStyle = “white”;
ctx.fillRect(111, 11, 34, 100);
ctx.fillStyle = “red”;
ctx.fillRect(156, 11, 249, 100);

ctx.fillStyle = “white”;
ctx.fillRect(11, 111, 394, 34);

ctx.fillStyle = “red”;
ctx.fillRect(11, 145, 100, 100);
ctx.fillStyle = “white”;
ctx.fillRect(111, 145, 34, 100);
ctx.fillStyle = “red”;
ctx.fillRect(156, 145, 249, 100);
});
</script>
</head>
<body>
<canvas id=”FirstCanvas” width=”416″ height=”256″>
<p>Flag of Denmark</p>
</canvas>
</body>
</html>


What we’ve created resembles the flag of Denmark!

HTML5 Multimedia Development Cookbook

There’s more…

This example may not seem overwhelming at first, but when you remember that we’ve created an image with hardly any HTML and no CSS whatsoever, the new canvas element starts to look pretty impressive.

Any way you want it

Note that while we used color names (“white” and “red”) we could also use hexadecimal values or RGB or even HSL! Use whatever makes the most sense for you and your interactive project.

Similar to tables?

Think of the color and size specifications for this example almost as the old-school tables we used to build back in the day for layout. While certainly not the same, there are definitely similarities to that technique in this case.

Be a square first

Mastering rectangles is the first canvas technique that’s important to have under your belt after the ability to set up the element itself. Understanding the basics of this approach will help you grasp the fundamentals of the next few recipes.

Drawing borders for images using canvas

Let’s take a closer look at the super simple method of drawing borders around images using the new canvas element.

How to do it…

First, we’ll start with our basic canvas code and add one new line to draw a border:

<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset=”utf-8″ />
<script
src=”http://ajax.googleapis.com/ajax/libs/jquery/1/
jquery.min.js”></script>
<script>
$(document).ready(function() {
var canvas = document.getElementById(“FirstCanvas”);
var ctx = canvas.getContext(“2d”);
ctx.strokeRect(10, 20, 100, 100);
});
</script>
</head>
<body>
<canvas id=”FirstCanvas” width=”800″ height=”600″>
<!– Fallback code goes here –>
</canvas>
</body>
</html>


HTML5 Multimedia Development Cookbook

How it works…

That one line of JavaScript tells the browser to create a rectangle starting at 10 pixels from the left and 20 pixels from the top of the new canvas element. It draws the box 100 pixels square.

There’s more…

That’s nice, but if we want the border to be any other color than the default, we’ll need to specify that:

<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset=”utf-8″ />
<script
src=”http://ajax.googleapis.com/ajax/libs/jquery/1/
jquery.min.js”></script>
<script>
$(document).ready(function() {
var canvas = document.getElementById(“myCanvas”);
var ctx = canvas.getContext(“2d”);
ctx.strokeStyle = “rgb(0, 128, 0)”;
ctx.strokeRect(10, 20, 100, 100);
});
</script>
</head>
<body>
<canvas id=”myCanvas” width=”600″ height=”600″>
<!– Fallback code goes here –>
</canvas>
</body>
</html>


In this case we’ve used strokeStyle to specify an RGB color of pure green.

HTML5 Multimedia Development Cookbook

Style first

If you plan to style a border, you’ll need to specify that before the border is drawn by the browser. If you specify that style afterward, the browser will simply ignore it.

Many color values work

The style attribute we just used was RGB, but the method also works with colors (“green”, for example), hexadecimal values, HSL, and RGBA.

I like big borders and I cannot lie

If no border width is specified, the browser will automatically draw a one-pixel border. Here’s how to change that:

<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset=”utf-8″ />
<script
src=”http://ajax.googleapis.com/ajax/libs/jquery/1/
jquery.min.js”></script>
<script>
$(document).ready(function() {
var canvas = document.getElementById(“myCanvas”);
var ctx = canvas.getContext(“2d”);
ctx.lineWidth = 10;
ctx.strokeStyle = “rgb(0, 128, 0)”;
ctx.strokeRect(10, 20, 100, 100);
});
</script>
</head>
<body>
<canvas id=”myCanvas” width=”600″ height=”600″>
<!– Fallback code goes here –>
</canvas>
</body>
</html>


It’s just this easy:

HTML5 Multimedia Development Cookbook

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here