HTML5 Canvas Fundamentals

Welcome to this review of HTML5 Canvas Fundamentals, which is the 7th and final course on the HTML5 Learning Path on Pluralsight, which is by Google GDE, Microsoft MVP and Regional Director Dan Wahlin.

DanWahlin

Dan Wahlin is your HTML5 Canvas Teacher

Although it is right at the end of the learning path, as long as you have done some web programming before you should have no problems watch and learning this without having seen any of the previous courses.

If you have done any work with 3D before, you will already know most of the mathematical concepts behind these API functions. But Dan Wahlin does not assume this and this course is accessible to virtually everyone.

Getting Started with the HTML5 Canvas

Dan Wahlin has a relaxed style of teaching. He finds simple analogies and uses them to present technical topics in simple ways. This makes it easier to remember what you’ve just been taught.

I like the way that he introduces Canvas: with scenarios of some ways in which you can use it: Games, Multimedia Apps and Charting.

Game Demos

canvasdemos.com appears to have changed for the worse since this course was published, however Ben Firshman’s JSNES is still available here. Awesome! I haven’t played Super Mario in years!

Pirates Love Daisies is free to play. Cut the rope and Angry Birds Chrome don’t appear to be free to play anymore.

I’ve also found some other fun demos:

blob sallad – moving a blob around the canvas, with or without gravity

source code here

CAKE – Canvas Animation Kit Experiment

and Missile Fleet by Ilmari Heikkinen

Mini Paint by viliusle

Also there’s a book by Jacob Seidelin called HTML5 Games: Creating Fun with HTML5, CSS3, and WebGL

Read the first chapter for free here

Engaging Applications

Dan shows off Tron and Firework, couldn’t find these at the same URLs but you get the idea clearly enough.

Charting

Check out these Flot Examples

Fundamentals

Dan explains that there is no built-in support for animations (unlike Silverlight/Flash etc)

He recommends defining a width and a height on the canvas tag rather than in CSS (it did not work for him at the time, but I will let you know whether this is old advice).

Any content you put inside the canvas is rendered if the canvas is not supported, so this is an easy fallback solution.

Hello World Demo

This will mostly already be familiar if you have watched the Canvas module in the HTML5 Fundamentals course, although I found this information easier to recall.

If you are an experienced programmer in a situation where you need to learn the Canvas API really fast, you should be able to skip the entire first module and start at the Drawing Rectangles and Ellipses clip.

Overview of the Canvas API

In the clip all 34 of the Canvas API functions are displayed on one screen. It’s nice to see that this is such a small, easy to learn API.

Later, the line and shape functions are highlighted, and there are 15 of these.

Then the text functions are described. There are only 3 of these: fillText, measureText and strokeText.

There are 6 transformation functions: restore, rotate, save, scale, transform and translate.

Demo: Canvas API Documentation

Dan describes the WHATWG documentation that you can find here, and also recommends the w3schools documentation, which includes some demos that you can play with.

Drawing with the HTML5 Canvas

Drawing Rectangles and Ellipses

There are 8 functions explained here:

  • arc(x, y, radius, startAngle, endAngle, antiClockwise)
  • arcTo(x1, y1, x2, y2, radius)
  • clearRect(x y, w, h)
  • fill()
  • fillRect(x y, w, h)
  • rect(x y, w, h)
  • stroke()
  • strokeRect(x y, w, h)

Demo: Simple Bar Chart

This is really nice. You can easily follow along and learn how to make various rectangles, in just a few minutes.

After the basics are understood, we see how to create a bar chart by using a for loop to iterate through an array.

Dan also briefly teaches how to debug in the Chrome browser (works similarly in other browsers)

This clip is available for free on YouTube.

Demo: Simple Bar Chart with Transforms

This demo includes translations and rotations, but still looks like a simple bar chart as before.

Demo: Drawing Circles

This is done using the arc function, see w3schools demo

Dan shows how to fill the circle, or just show the outline, or show a filled circle with a border.

We also see how to create half circles and slices of a circle, and displaying circles on top of each bar on the chart.

Demo: Using arcTo()

This demo uses four arcTo functions to render a rectangle with rounded corners.

Drawing Lines and Paths

There are 7 line and path functions:

  • beginPath()
  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
  • closePath()
  • lineTo(x, y)
  • moveTo(x, y)
  • quadraticCurveTo(cpx, cpy, x, y)
  • stroke()

Dan explains how these work.

Demo: Drawing Lines

First we see how to create a triangle. Then we see a variety of looks for the edge points using the lineJoin, miterLimit and lineCap functions.

We also see it filled in.

Demo: Simple Line Chart

This demo uses beginPath, lineWidth, moveTo, stroke and closePath functions

Demo: Using bezierCurveTo()

This function uses six arguments, e.g.

  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

In this demo, Dan fills in the bezier curve, creating half an ellipse, and then changes the argument values to create some more interesting shapes.

Demo: Using quadraticCurveTo()

This is a little simpler than bezierCurveTo with 4 arguments:

  • quadraticCurveTo(cpx, cpy, x, y)

This curve shape reminds me of the Nike swish.

Drawing Text

There are just three functions for this:  fillText, measureText and strokeText.

Demo: Filling, Stroking and MeasuringText

Well this is certainly a whole lot easier than doing tons of lineTo functions. Dead easy!

Dan shows the font property, setting it to fontSize + ‘px Arial’;

Demo: Using Canvas Transforms with Text

Here we see how to rotate text, which is useful if you are doing a chart and need some text on it’s side.

This demo uses translate, rotate and save functions.

Drawing Images

There are 3 relevant image functions:

Demo: Using Image Functions

This demo explains createPattern with the various patterns:

  • repeat-x
  • repeat-y
  • repeat
  • no-repeat

It also explains toDataURL including the cross domain security restriction.

Drawing Video

This is where it begins to get a lot more interesting for me, because apart from a few specific use cases, I don’t see much point in using canvas to create static images when it is more reliable and often easier to just display a gif/png/jpeg image (or just use CSS).

  • drawImage(video, destX, destY, destWidth, destHeight)

Demo: Syncing Video with a Canvas

This demo uses an addEventListener for ‘play’, ‘pause’ and ‘ended’.

The rendering speed of this demo is impressive. I could not see any difference in quality between the original video and the canvas copy of it.

Manipulating Pixels

Rendering Gradients

3 functions:

These are some more powerful functions for creating aesthetically pleasing images potentially quicker than it would take to create in a graphics program.

Demo: Creating Linear Gradients

This is quite easy to do and has some advantages over the old CSS solution.

Demo: Creating Radial Gradients

A little more involved but creates a nice lighting effect on a circle.

Using Transforms

This section talks about the following functions:

  • restore()
  • rotate(angle)
  • save()
  • scale(x, y)
  • setTransform(scale-x, skew-x, skew-y, scale-y, translate-x, translate-y)
  • transform(scale-x, skew-x, skew-y, scale-y, translate-x, translate-y)
  • translate(x, y)

Dan introduces matrix algebra here.

He says setTransform wipes things out whereas transform works with what you already have.

Demo: Getting Started with Transform Functions

This example rotates a rectangle ans some text. It illustrates the importance of the save and restore functions.

Demo: Using transform() and setTransform()

This nice little interactive demo shows off the effect of changing the various transform values. There are textboxes with up and down sliders so that you can change the scale, skew and translate values in both dimensions.

This is followed by an even better demo which uses the sine and cosine functions to create different values for the transform and create overlapping, randomly colored squares going round in a circle.

Accessing Pixels

This section covers following function definitions:

  • createImageData(width, height)
  • createImageData(imgData)
  • getImageData(x, y, width, height)
  • putImageData(imgData, dx, dy, x, y, width, height)

Dan explains that every pixel is composed of four components:

  • red
  • green
  • blue
  • alpha

Demo: Creating Pixels Dynamically

The demo shows how to create different pixels using createImageDate followed by a nested for loop (one for loop for rows and another for columns)

This creates an interesting looking blue diamond effect with many rotated nested blue squares.

By changing different parameter values here, you can experiment with using mathematics to create art.

Demo: Grayscale Pixels

HTML5_Logo_512HTML5_1Color_Black

This example creates a function that converts the HTML5 logo into a greyscale version of it.

Animation Fundamentals

HTML5 canvas doesn’t natively support animations so you need to write your own native JavaScript code to do this.

Dan describes a couple of different techniques along with their pros and cons

window.setInterval

window.requestAnimationFrame

See browser support for requestAnimationFrame on can i use?

Dan shows some code that uses requestAnimationFrame if available and falls back to using setTimeout if unavailable.

For some useful code snippets see Joe Lambert’s Gist

Demo: Getting Started with Animation

This example shows a moving circle, which looks like a ball bouncing off the browser “walls”

Demo: Using Gradients, Transforms and Animations

This example brings together many of the techniques described in this module to produce a clock animation.

Building a Custom Data Chart

Creating the CanvasChart Object

In this module we create an object that can:

  • Render lines and points
  • Display text on x and y axes
  • Use of gradients
  • Built-in animations as chart loads
  • Mouse interactions
  • Dynamic data overlay
  • Setting object that allows control over how the chart renders

This code uses one of Dan’s favorite design patterns: the Revealing Module Pattern

Creating the CanvasChart Shell code

This demo creates a CanvasChart function which contains the following functions:

  • render
  • renderParts
  • getMaxDataYValue
  • createOverlay

Rendering Text and Gradients

This adds the following functions:

  • renderBackground
  • renderText

By the end of this clip we have the background rendered and labels displayed

Rendering Data Points Text and Guide Lines

This adds the following functions:

  • renderLinesAndLabels
  • drawLine

By the end of this clip we have the years and the population data point values showing

Connecting Data Point Lines

This clip shows and explains the code that renders the line across the chart

Rendering Data Points

This uses the arc function to render lines on our chart. This creates the following functions:

  • drawPoints
  • renderCircle

By the end of this clip there are circles (with 3D effect) at each point on the line.

Adding Animation

This clip updates the drawPoints function and adds a clear function

For the requestAnimationFrame, this code is take from Paul Irish, see

requestAnimationFrame for smart rendering

By the end of this clip we see an animation for the creation of the line chart

Adding Overlays and Interactivity

In this clip Dan adds an overlay div. The end effect is to change the color of the circle from green to red when the user’s mouse goes over it, and the value display in the overlay div.

Summary

My main takeaway from watching this course is the Canvas API is easy to use. Although there is no native animation support, animation is not too hard to do, and there are many use scenarios for this technology.

Recommended Speed: x1.5

 

One thought on “HTML5 Canvas Fundamentals

  1. Pingback: HTML5 Learning Path | Zombie Code Kill

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s