Interested in CSS animation? Check out Creating Animations with CSS, a complete course on CSS Transitions and Keyframes animation by expert web developer Donovan Hutchinson, available for SitePoint members. For a sample of HTML5 canvas animations, watch Illustrations with the HTML5 Canvas below, it’s one video in our Start Animating with the HTML5 Canvas mini course.
One of the most important instruments in a painter’s toolkit is their canvas. It gives them the freedom to express all kinds of feelings, impressions, ideas, and so forth, in almost unlimited variations and combinations. And that freedom can be restricted only by two things — their skill level and their imagination.
The situation in the web development world is similar. With the ongoing progress of HTML5 and its powerful specifications, web developers have gained the ability to do things that were impossible in the past. Drawing graphics and creating animations directly in the browser is now completely possible thanks to a technology called HTML5 Canvas.
What is HTML5 Canvas?
The canvas element is an element defined in HTML code using
What’s so Great About HTML5 Canvas?
Here are some reasons you might want to consider learning to use HTML5’s canvas feature:
- Interactivity. Canvas is fully interactive. It can respond to a user’s actions by listening for keyboard, mouse, or touch events. So a developer is not restricted to only static graphics and images.
- Animation. Every object drawn on the canvas can be animated. This allows for all levels of animations to be created, from simple bouncing balls to complex forward and inverse kinematics.
- Flexibility. Developers can create just about anything using canvas. It can display lines, shapes, text, images, etc. — with or without animation. Plus, adding video and/or audio to a canvas application is also possible.
- Browser/Platform Support. HTML5 Canvas is supported by all major browsers and can be accessed on a wide range of devices including desktops, tablets, and smart phones.
- Popularity. Canvas popularity is rapidly and steadily growing so there is no shortage of resources available.
- It’s a web standard. Unlike Flash and Silverlight, Canvas is open technology that’s part of HTML5. And although not all of its features are implemented in all browsers, developers can be certain canvas will be around indefinitely.
- Develop once, run everywhere. HTML5 Canvas offers great portability. Once created, Unlike Flash and Silverlight, a canvas application can run almost anywhere — from the largest computers to the smallest mobile devices.
- Free and accessible development tools. The basic tools for creating HTML5 canvas applications are just a browser and a good code editor. Plus, there are many great and free libraries and tools to help developers with advanced canvas development.
What Applications Can You Create with HTML5 Canvas?
OK, canvas is great. But what exactly can use it for? Let’s see.
- Gaming. The HTML5 Canvas’ feature set is an ideal candidate for producing all sorts of 2D and 3D games.
- Advertising. HTML5 Canvas is a great replacement for Flash-based banners and ads. It has all the needed features for attracting buyers’ attention.
- Data Representation. HTML5 can collect data from global data sources and use it to generate visually appealing and interactive graphs and charts with the canvas element.
- Education and Training. HTML5 canvas can be used to produce effective and attractive learning experiences, combining text, images, videos, and audio.
- Art and Decoration. With a little bit of imagination and canvas’s wide variety of colors, gradients, patterns, transparency, shadows, and clipping features, all kinds of artistic and decorative graphics can be drawn.
Now that we know why we should learn canvas, let’s look at the basics of HTML5 Canvas and how to start using it.
Canvas Rendering Contexts
Every HTML5 canvas element must have a context. The context defines what HTML5 Canvas API you’ll be using. The 2d context is used for drawing 2D graphics and manipulating bitmap images. The 3d context is used for 3D graphics creation and manipulation. The latter is actually called WebGL and it’s based on OpenGL ES.
To get started with canvas, all you need is a code editor and a browser with HTML5 canvas support. I use Sublime Text and Google Chrome, but you can use whatever you want.
Our HTML to start will look like this:
<canvas id="exampleCanvas" width="500" height="300"> <!-- OPTION 1: leave a message here if browser doesn't support canvas --> <p>Your browser doesn’t currently support HTML5 Canvas. Please check caniuse.com/#feat=canvas for information on browser support for canvas.</p> <!-- OPTION 2: put fallback content (text, image, Flash, etc.) if the browser doesn't support canvas --> </canvas>
var canvas = document.getElementById('exampleCanvas'), context = canvas.getContext('2d'); // code examples will continue here...
By default, the browser creates canvas elements with a width of 300 pixels and a height of 150 pixels, even if these aren’t specified in the HTML. You can change the size by specifying the
height, as I’ve done in the HTML.
Notice also that we’ve given the canvas an
Notice that between the opening and closing
<canvas> tags, I’ve added content that will be displayed if the browser doesn’t support canvas. This can be just about any type of content that an older browser supports.
context) that references the 2D context for the canvas using the
getContext() function. We’ll use the
context variable to access all canvas drawing functions and properties.
With our canvas ready to go we can start experimenting with the Canvas API. But before that, let’s clarify a few more aspects of the canvas feature.
HTML5 Canvas Element Size vs. Drawing Surface Size
Besides the canvas element’s
height attributes, you can also use CSS to set the size of a canvas element. However, sizing a canvas element with CSS is not the same as setting the element’s
height attributes. This is because a canvas actually has two sizes: the size of the element itself and the size of the element’s drawing surface.
When you set the element’s
height attributes, you set both the element’s size and the size of the element’s drawing surface; however, when you use CSS to size a canvas element, you set only the element’s size and not the drawing surface. When the canvas element’s size does not match the size of its drawing surface, the browser scales the drawing surface to fit the element.
Because of this, it’s a good idea to use the canvas element’s
height attributes to size the element, instead of using CSS.
Understanding the Canvas Coordinate System
In a 2D space, positions are referenced using X and Y coordinates. The X axis extends horizontally, and the Y axis extends vertically. The center has a position
x = 0 and
y = 0, that can also be expressed as
(0, 0). This method of positioning objects, used in mathematics, is known as the Cartesian coordinate system.
The Canvas coordinate system, however, places the origin at the upper-left corner of the canvas, with X coordinates increasing to the right and Y coordinates increasing toward the bottom of the canvas. So unlike a standard Cartesian coordinate space, the Canvas space doesn’t have visible negative points. Using negative coordinates won’t cause your application to fail, but objects positioned using negative coordinate points won’t appear on the page.
Basic Canvas Examples
As mentioned, HTML5 Canvas let’s you create many types of objects, including lines, curves, paths, shapes, text, etc. In the examples to follow you can see how some of these objects are actually drawn. I won’t go in extensive detail on the Canvas API; these are just some easy to help you get a feel for how canvas works.
To draw a line, we use four canvas API methods. We start with the
beginPath() method which instructs the browser to prepare to draw a new path. Next, we use the
moveTo(x, y) method to set the line’s starting point. Then
lineTo(x, y) method sets the ending point and draws the line by connecting the two points.
At this point the line will be drawn, but it’s still invisible. To make it visible we use the
stroke() method to display the line with the default black color.
context.beginPath(); context.moveTo(50, 50); context.lineTo(250, 150); context.stroke();
To draw a rectangle, we can use the
fillRect(x, y, width, height) method to set the coordinates and the dimensions, along with the
fillStyle property to set the fill color.
context.fillStyle = 'yellow'; context.fillRect(50, 50, 200, 100);
Notice that the rectangle is positioned near the top left corner.
To draw text on the canvas, we can use
fillText(string, x, y) along with the
font property to set the font, size, and style of the text (similar to font shorthand in CSS).
context.font = 'italic 40pt Calibri, sans-serif'; context.fillText('Hello World!', 50, 50);
Where to Learn More?
If you want to learn here are some resources:
- Canvas tutorial – An excellent tutorial on MDN, full of examples, illustrations, and detailed explanations.
- HTML5 Canvas Element Guide – A beginner’s tutorial from Six Revisions.
- HTML5 Canvas tutorials – A full set of tutorials created by Eric Rowell, the creator of the KineticJS canvas library. All examples are interactive; you can play with them and see the result immediately.
Speed Up Canvas Development
Working with the “raw” HTML5 Canvas API can be a tedious job. That’s why it’s a good idea when you learn it well to switch to a good canvas library that can speed up and make your canvas development a lot easier.
Here are some popular choices:
That’s it. I hope this introductory HTML5 Canvas tutorial has given you a good starting point from which to continue your learning and exploring of this powerful technology.