Beruflich Dokumente
Kultur Dokumente
Canvas
By Malcolm Sheridan
Undoubtedly, the canvas element in HTML5 is the biggest feature that developers will want to use to develop
truly rich web applications without needing to install browser plug-ins like Adobe's Flash player. IE9 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, try learning more here.
Canvas 2D API
The 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. Heres the snippet of code for referencing the context.
Each canvas has its own context, so if youre page contains multiple canvas elements; you must have a
reference to each individual context that 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.
State Functions
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.
Text Functions
Text Functions
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.
As you can imagine there are more methods attached to the canvas 2D API. Check out this page for all the
methods that I haven't covered in this section.
The canvas is pretty dull if you dont draw on it, so lets take a look at what you can draw once you have the
context.
If you dont specify a colour, the default colour will always be black. To draw another rectangle on top, call
fillRect again with different parameters. The fillStyle can be any CSS colour, so it can take advantage of the
new opacityproperty in CSS3. The following code draws three rectangles on the canvas, and changes the
colour of the bottom one so its semi transparent.
Heres the result.
Drawing circles is a breeze too. To draw a cirlce, the easiest way is to use arc. This draws a circle on the
canvas using the current fillStyle. The function's definition is below.
arc(x, y, radius, startAngle, endAngle, anticlockwise) - asds 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
Here's how to create a black circle.
To draw the outline of a circle, use strokeStyle instead of fillStyle. Then call stroke instead of fill.
Circles dont have to be 360 degrees. To alter the shape, change the start and end radius.
Heres the semi circle.
Moving away from circles and into something more advanced, lets look at drawing Bezier curves. This tough
task is made relatively simple by using the bezierCurveTo function. This adds points to the current subpath
by using the control points that represent a Bzier curve. The parameters for bezierCurveTo are below.
bezierCurveTo (cp1x, cp1y, cp2x, cp2y, x, y) - adds the given point to the current path, connected to the
previous one by a cubic Bzier curve with the given control points
A Bezier curve must include three points. The first two points control the calculation, and the third point is the
ending point for the curve. Heres how to create a simple Bzier curve.
1.
2.
3.
4.
5.
context.lineWidth = 20;
context.beginPath();
context.moveTo(5, 50);
context.bezierCurveTo(30, 30, 130, 530, 200, 100);
context.stroke();
Bzier curves give you a great amount of power to draw with. Heres an advanced example of drawing a
smiley face on a canvas.
The image below displays the smiley face.
To complement the shapes capable on the canvas, you can also mix up the colours either by a solid colour,
outline, gradient or pattern. Ive used fillStyle mostly in the previous examples. This function fills the
background of the context with a solid colour. This can be a multitude of colours. The following example will
randomise the background colour of the canvas and produces a rainbow effect.
The effect can be seen in the image below.
If you don't want solid colours, you can use strokeStyle and strokeRect to draw the outline of a rectangle.
Another feature of canvas gives to the ability to create gradients. The related function for this are below.
addColorStop(offset, color) - adds a colour 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 coordinares
A linear gradient can be created by calling createLinearGradient. To add colour to the gradient you call
addColorStop. Calling this adds the specified colour at the x and y coordinates. The following example
demonstrates a simple linear gradient.
The gradients can be seen below.
There's a lot more on gradients that I haven't covered. For the full picture you should check out the W3C
website here.
To add some pizzazz to the lines, you can also change what's known as the cap, or the end shape of the line
by setting the lineCap property. To create a rounded edge, I can set the lineCap to round.
Doing that to the example draws the rounded lines.
As well as lines, text is simple to draw on a canvas element. Unlike text on a web page, there's no box model,
which means the CSS that you're familiar with is not available. But you do have options. Some of the related
properties and functions for drawing text are below.
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
To print some plain text use fillText. I'm setting the font size and type by using the font property.
Here's the result.
Adding effects like shadows is a piece of cake too. The following code uses the shadow drawing objects to
create the shadow.
The shadow can be customised to create any angle or shadow colour you like. I've only demoed a small
fraction of what you can do with text on the canvas. For more information on this, check out the Text
sectionon W3C.
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
tonne of functionality attached to this element, so before we begin, you should read up about it here. The
tonne 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.
Ill first add the canvas and video HTML.
Not much is happening here. The video will play inside the video tag, but Im going draw the video on the
canvas and position the video centrally on the canvas. The result is awesome. Heres the code.
The trick to making this work is to recursively draw the video on the canvas, otherwise itll 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.
The still image does this demonstration no favours, so to see the animation working you can go here.
Scaling canvas elements is easy too. Ill stick with the previous demo, except for rotating; Ill scale out each
rectangle ever second. Heres the code.
The image below displays the result.
Again the image will not show the animation, so to see the animation working you can go here. As you can
imagine this is just a starting point for transformations and animations. For a complex animation, you can
take a look at Brilliant Lines, which was created by the W3C group. That can be found here. For more
information on transformations, you should go here.