Undoubtedly, the canvas element in HTML5 is the feature that most developers will want to use to develop truly rich web applications – without needing to install browser plug-ins like Adobe’s Flash player. Canvas was born at a time when client richness is at the forefront of developers’ minds. Modern browsers like Chrome, Firefox, and Internet Explorer 9 and 10 all support it. But what exactly is the canvas element in HTML5? How can you use it to create rich web applications? If you’re unfamiliar with HTML5, before diving into this article you might like to read Yes, You Can Use HTML5 Today! and HTML5 and Even Fancier Forms.
- the canvas is faster at drawing complex graphics
- you can save images off the canvas whereas you can’t using SVG
- everything in the canvas is a pixel.
- it’s resolution independent so it can scale for different screen resolutions
- it’s xml, so targeting different elements is a breeze
- it’s good at complex animations
Canvas 2D APIThe canvas 2D API is an object that allows you to draw and manipulate images and graphics on a canvas element. To reference the context of the canvas, you call getContext, which is a method on the canvas element. It has one parameter, which currently is 2d. Here’s the snippet of code for referencing the context. Each canvas has its own context, so if your page contains multiple canvas elements you must have a reference to each individual context you want to work with. Aside from getContext, there are plenty of other functions at your disposal in the canvas 2D API. Some of the notable ones are outlined below. Transformation Functions
- scale – allows you to scale the current context.
- rotate – allows you to rotate the x and y coordinates of the current context.
- save – allows you to save the current state of the context.
- restore – allows you to restore the state of the context from a previously saved state.
- font – gets or sets the font for the current context.
- fillText – renders filled text to the current canvas.
- measureText – measures the current width of the specified text.
Shapes & ColorsThere’s an entire group of properties and functions devoted to drawing shapes. Let’s begin with rectangles. Here are the related functions available to draw rectangles.
- fillRect(x, y, w, h) – draws the given rectangle onto the canvas, using the current fill style
- strokeRect(x, y, w, h) – draws the box that outlines the given rectangle onto the canvas, using the current stroke style
- clearRect(x, y, w, h) – clears all pixels on the canvas in the given rectangle to transparent black
- arc(x, y, radius, startAngle, endAngle, anticlockwise) – points to the subpath such that the arc described by the circumference of the circle described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction, is added to the path
- bezierCurveTo (cp1x, cp1y, cp2x, cp2y, x, y) – adds the given point to the current path, connected to the previous one by a cubic Bézier curve with the given control points
- addColorStop(offset, color) – adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the opposite end
- createLinearGradient(x0, y0, x1, y1) – returns a CanvasGradient object that represents a linear gradient that paints along the line given by the coordinates
- createRadialGradient(x0, y0, r0, x1, y1, r1) – returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the circles represented by the coordinates
Lines, Text & ShadowsWhen you’re drawing lines, think of paths. Each canvas has a path. Defining a path is like drawing a line. Any line is possible. Just like writing, you need to define a path, and then fill the path in. Here are some of the related properties and functions for drawing lines.
- lineWidth [ = value ] – returns the current line width. Can be set to change the line width
- lineCap [ = value ] – returns the current line cap style. Can be set to change the line cap style. The possible line cap styles are butt, round, and square
- lineJoin [ = value ] – returns the current line join style. Can be set to change the line join style. The possible line join styles are bevel, round, and miter
- font [ = value ] – returns the current font settings. Can be set, to change the font. The syntax is the same as for the CSS ‘font’ property
- textAlign [ = value ] – returns the current text alignment settings. Can be set, to change the alignment. The possible values are start, end, left, right, and center
- textBaseline [ = value ] – returns the current baseline alignment settings. Can be set, to change the baseline alignment
- fillText(text, x, y [, maxWidth ] ) – fills the text at the given position
- strokeText(text, x, y [, maxWidth ] ) – strokes the text at the given position
Images & VideoWell, when you’re working with the canvas, it’s possible to work with images and videos too. The obvious question is why not just use a standard <img> element? Well the big advantage is your image can be part of a much bigger and complex image thanks to all the wizardry you can create with the canvas element. There’s one main function for working with images and videos, and that’s drawImage. The following piece of code references the sheep image and draws that on the canvas. That code draws the sheep on the canvas. The image can now be rotated, flipped, faded in and out or simply spun around now that it’s drawn on the canvas. Videos follow a similar path. First you need to use the HTML5 video element. As you can imagine, there’s a ton of functionality attached to this element, so before we begin, you should read up about it here. The video element on its own is not that interesting. The element itself contains a controls attribute, which determines if the browser should display the standard set of video controls, and loop which tells the browser if the video is recursive. Inside the video element you specify three children, each with the same video, but with different formats. Nothing new here, but when you team the video element with the canvas … well, you can come up with some amazing things. I’ll first add the canvas and video HTML. Not much is happening here. The video will play inside the video tag, but I’m going draw the video on the canvas and position the video centrally on the canvas. The result is awesome. Here’s the code. The trick to making this work is to recursively draw the video on the canvas, otherwise it’ll only be drawn once, and that would look pretty awful. This is why setInterval is called when the page loads. The live video can be seen here.
Transformations & AnimationsTransformations and animations are possible with the canvas element. Here are some of the related properties and functions for performing transformations.
- scale(x, y) – changes the transformation matrix to apply a scaling transformation with the given characteristics
- rotate(angle) – changes the transformation matrix to apply a rotation transformation with the given characteristics
- translate(x, y) – changes the transformation matrix to apply a translation transformation with the given characteristics
- transform(m11, m12, m21, m22, dx, dy) – changes the transformation matrix to apply the matrix given by the arguments
- setTransform(m11, m12, m21, m22, dx, dy) – changes the transformation matrix to the matrix given by the arguments.
- HTML5 Canvas Developer Guide on MSDN
- Hardware Accelerated Paintball Canvas Demo
- How to Choose Between Canvas and SVG to Create Web Graphics
Frequently Asked Questions (FAQs) about HTML5 Canvas
How can I increase the resolution of my HTML5 canvas?
Increasing the resolution of your HTML5 canvas involves adjusting the width and height properties of the canvas. You can do this by setting the width and height attributes of the canvas element in your HTML code. However, remember that this will only change the size of the canvas, not the actual resolution. To increase the resolution, you need to scale the context of the canvas using the scale() method. This method takes two parameters: the scale factor for the x-axis and the y-axis. For example, context.scale(2,2) will double the resolution of your canvas.
What is the purpose of the HTML5 canvas element?
How can I draw shapes using HTML5 canvas?
Drawing shapes on an HTML5 canvas involves using specific methods provided by the canvas API. For instance, to draw a rectangle, you can use the fillRect() or strokeRect() methods. These methods take four parameters: the x and y coordinates of the top-left corner of the rectangle, and the width and height of the rectangle. To draw a circle, you can use the arc() method, which takes six parameters: the x and y coordinates of the center of the circle, the radius, the start angle, the end angle, and a boolean value indicating whether the arc should be drawn counterclockwise.
How can I add text to my HTML5 canvas?
Adding text to an HTML5 canvas involves using the fillText() or strokeText() methods. These methods take three parameters: the text string, and the x and y coordinates where the text should be drawn. You can also use the font property to specify the font size and family, and the textAlign and textBaseline properties to align the text.
How can I draw images on my HTML5 canvas?
Drawing images on an HTML5 canvas involves using the drawImage() method. This method can take three, five, or nine parameters, depending on whether you want to draw the entire image or a portion of it, and whether you want to scale the image or not. The simplest way to use this method is to pass it the image object and the x and y coordinates where the image should be drawn.
How can I clear my HTML5 canvas?
Clearing an HTML5 canvas involves using the clearRect() method. This method takes four parameters: the x and y coordinates of the top-left corner of the rectangle to clear, and the width and height of the rectangle. To clear the entire canvas, you can pass it the coordinates (0,0) and the width and height of the canvas.
How can I save and restore the state of my HTML5 canvas?
Saving and restoring the state of an HTML5 canvas involves using the save() and restore() methods. The save() method saves the current state of the canvas, including the transformations, the clipping region, and the values of the properties. The restore() method restores the most recently saved state.
How can I apply transformations to my HTML5 canvas?
Applying transformations to an HTML5 canvas involves using methods like translate(), rotate(), and scale(). The translate() method moves the canvas and its origin to a new location. The rotate() method rotates the canvas around the current origin. The scale() method scales the canvas units by x horizontally and by y vertically.
How can I create animations with my HTML5 canvas?
Creating animations with an HTML5 canvas involves changing the drawings on the canvas over time. This can be done by using a loop that repeatedly clears the canvas and redraws the shapes in new positions. The most common way to create such a loop is to use the requestAnimationFrame() method, which tells the browser to execute a specified function before the next repaint.
How can I handle events on my HTML5 canvas?
Handling events on an HTML5 canvas involves adding event listeners to the canvas element. These listeners can respond to events like mouse clicks, mouse movements, and key presses. The event object passed to the event handler function contains information about the event, such as the position of the mouse or the key that was pressed.