Web Programming Step by Step, 2nd Edition

Lecture XX: HTML5 Canvas

Reading: No Reading

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

Flash Content

flash in gmail


flash compilation

Linking to multimedia files

<a href="video.avi">My video</a>

File types and browser plugins

browser plugins

Embedded objects: <object>

<object data="video.avi" type="video/avi"></object>

Parameters: <param>

<object id="slider1" width="100" height="50">
	<param name="BorderStyle" value="thick" />
	<param name="MousePointer" value="hourglass" />
	<param name="Enabled" value="true" />
	<param name="Min" value="0" />
	<param name="Max" value="10" />

Using Flash Content

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
	<param name="movie" value="movie_name.swf"/>
	<!--[if !IE]>-->
	<object type="application/x-shockwave-flash"
		<p> Alternate content goes here. Similar to an img tag's alt text. </p>
	<!--[if !IE]>-->


<script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<div id="my_id">
	<p>Please download Flash!</p>
swfobject.embedSWF(swfUrl, "my_id", width, height, version);

swfobject example

<div id="flashMovie">
	<p>Please download Flash!</p>
		"flashMovie", "550", "400", "9.0.0");

Please download Flash!

The way of the future: HTML5 Canvas

apple is killing flash

No really, javascript DrawingPanel!

  1. Create a canvas element
    <canvas id="mycanvas" width="200" height="150"></canvas>
  2. Get a reference to the context from which we can draw things, remember Graphics g
    var ctx = document.getElementById("mycanvas").getContext("2d");
  3. Go "DrawingPanel" nuts!
    ctx.fillStyle = "#FF0000";
    ctx.strokeStyle = "#00FF00";
    for (var i = 0; i < 10; i++) {
    	ctx.fillRect(i * 20, i * 10, 400 - i * 40, 200 - i * 20);
    	ctx.strokeRect(i * 20, i * 10, 400 - i * 40, 200 - i * 20);

Canvas context Methods

canvas method DrawingPanel analog
ctx.fillText(string, x, y); g.drawString(str, x, y);
ctx.fillRect(x, y, width, height); g.fillRect(x, y, width, height);
ctx.arc(x, y, radius, startAngle, endAngle);
g.drawOval(x, y, width, height);
ctx.moveTo(x1, y1);
ctx.arc(x2, y2);
g.drawLine(x1, y1, x2, y2);
ctx.fillStyle = "#FF0000" g.setColor(color);

Exercise: canvas Chess

canvas chess board

Here is a working example of canvas chess.

  • Draw a chess board pattern using a canvas
  • Add chess pieces using one character strings for each
    • K for King, Q for Queen, etc...

canvas issues

jCanvas jQuery plugin

jCanvas methods

method options
$('#mycanvas').drawRect({...}); x, y, width, height
$('#mycanvas').drawPolygon({...}); x, y, radius, sides
$('#mycanvas').drawLine({...}); x1, y1, x2, y2, x3, y3, ...
$('#mycanvas').drawArc({...}); x, y, radius, start, end
$('#mycanvas').drawText({...}); x, y, text
$('#mycanvas').draw(function(ctx) { ... });

jCanvas options

These options are generally accepted by all drawing methods.

option description
fillStyle color to use for interior of shape if any
strokeStyle color to use for the outline of the shape or for lines
strokeWidth thickness of lines or outlines
fromCenter whether coordinates are relative to center of shape
rotate a rotation to apply to a shape or line
layer whether to stick the drawing in a layer, defaults to false
name a name to give to a layer, presumes layer: true
group the group to associate this layer with, presumes layer: true

Exercise: jCanvas Chess

Here is a working example of jCanvas chess.

  • Create a second version of canvas chess that uses jCanvas
    • Can we improve the placement of the pieces?
    • Can we make any functions take fewer parameters?

jCanvas defaults

jCanvas custom shapes

  'name': 'drawHeart',
  'props': {
    faded: false
  'fn': function(ctx, p) {
    // Draw a heart using the DOM canvas API

// Use the drawHeart method
	'faded': true,
	'strokeWidth': 4

jCanvas layers

layered drawing

jCanvas layers example

jCanvas layer groups

jCanvas addLayer() mistake

// Manual layers are not drawn immediately, seemingly does nothing
	'method': 'drawArc'
	'layer': true,
	'strokeStyle': '#000000',
	'radius': 30,
	'x': 150, 'y': 50
// Solution: tell jCanvas to draw the layers now

Exercise: jCanvas layers

  • Add layers to our jCanvas chess code
    • Put the board tiles in their own layer group
    • Put the tile borders in their own layer group
    • Put the chess pieces in their own layer group
  • Reduce the redundancy in our code by setting group defaults

jCanvas events

jCanvas event example

	'layer': true,
	'fillStyle': '#ff0000',
	'x': 50, 'y': 50,
	'width': 20, 'height': 20,
	'click': clickHandler

function clickHandler(layer) {
	layer.x += 10;

jCanvas animation

	'layer': true,
	'name': 'foo',
	'fillStyle': '#ff0000',
	'x': 50, 'y': 50,
	'width': 20, 'height': 20,
}).animateLayer('foo', {
	'x': 250
}, 'slow');

jCanvas events and animation example

	'layer': true,
	'name': 'foo',
	'fillStyle': '#ff0000',
	'x': 50, 'y': 50,
	'width': 20, 'height': 20,
	'click': clickHandler

function clickHandler(layer) {
	$(this).animateLayer('foo', {
		'x': 250,
		'fillStyle': '#00ff00'
	}, 'slow');

Exercise: jCanvas chess pawn clicks

  • make it so that the bottom pieces move smoothly up one square when you click them
    • Hint: Use a click event handler with an animation