Basic HTML5 Canvas Methods Every Designer Should Know

Inspired Magazine
Inspired Magazine – creativity & inspiration daily

Using the canvas of HTML5 should have become second nature by now, but actually it’s still very rarely utilized by designers.  This could be in part due to the fact that the average business site has no great need to make use of canvas features, but that’s not always the case, and understanding how to use the canvas is an essential skill that every designer should have at least some familiarity with.

The canvas provides a way to draw and animate directly on the web page, and as such it allows the creation of real-time graphics that can be quite useful in a variety of ways.  For example, you could make charts that indicate live stock value fluctuations.  Or you could just draw a cartoon mouse being chased by a herd of hungry velociraptors.  What you draw depends on the needs of the job.  How you draw it depends on your skills as a designer.

Setting up canvas objects

The canvas object actually existed before HTML5, but it wasn’t something natively supported.  You could create it in code with graphics libraries like Raphaël, but you couldn’t declare it as any other HTML element.

Example – setting up a canvas object in HTML4 with Raphaël:

Example – setting up a canvas object in HTML5 natively:

As you can easily see, it is a much simpler matter to create a canvas object in HTML5 than it was to do something remotely similar in previous versions of HTML.

The default HTML5 canvas is a magical thing that can apparently only be seen by animals and perhaps small children.  Therefore anyone else wanting to see the canvas object as an object will need to apply some CSS rules (like a border, for example).  This is fine, because most of the time we won’t want to see the canvas, only whatever is drawn on top of it.

It is also best, in most situations, to set the display type of canvas to “block”, in order to prevent any strange behaviors caused by layout quirks.

The above code example sets up a canvas object 800px wide and 450px high (16:9 aspect ratio) and makes sure there is nothing nearby that might accidentally encroach upon the canvas space.

Every canvas should, as shown, have an id attribute, so you can specify which canvas any drawing routine is supposed to be sending output to.

Drawing to the canvas requires JavaScript

While HTML5 supplies the canvas object, it can’t actually draw anything on it without help from a script.  You can create a drawing by directly drawing an SVG image in HTML without using scripts, but this doesn’t require a canvas object.

Drawing to a canvas with JavaScript requires firstly identifying which canvas is to be drawn to (using the getElementByID method), and then defining the drawing context (either 2D or 3D) using the canvas.getContext method.  Both need to be initialized as variables.  As an example:

The above initializes the required variables for drawing to canvas01.  The next step would be to include an actual drawing instruction in the drawToCanv01 function. Doing any kind of drawing, we refer to the context variable (in the example it is identified as “ctx”), and execute any of the available JavaScript drawing methods on that context.

List of JavaScript drawing methods

There are not too many drawing commands to master, but there is enough complexity that it usually takes a while to master them all.  The problem is that there’s no really simple methods like you get with normal SVG drawing.  In JavaScript, you often need to use multiple commands together to produce a single result.  On the positive side, drawing commands in JavaScript use a much simpler syntax than SVG drawing commands.

These methods will each be explained in detail in a moment.  One thing you may have noticed is that these methods only tell the browser what to draw, but not how to draw it.  For that, you need to use a style one of the style methods indicated in the following table.

Drawing like a professional requires planning like one

You definitely can just sit down and bash out a drawing by trial and error, but that is a slow process for most of us.  The professional way to design canvas drawings is to sketch them on graph paper first.  You should always define a precise height and width for your canvas, and ideally set these values in pixels, because that will give you very precise coordinates.

Work out the scale of your sketch, and then mark pixel units along the X and Y planes.  Usually a sketch is plotted 1:1, but if you have a big drawing you might need to use 1:10 or even higher.  The top left corner is always 0,0 and if you are using a 1:1 scale then the point of the first major line intersection on the graph paper will be at position 10,10.

Then just use a pencil to draw your sketch.  With this sketch in hand, it is now very easy to translate your physical drawing onto the canvas because you have the precise coordinates for each part.  This is especially useful for circular objects, because it makes it easy to find their center point.

Make sure you remember that the order you issue your drawing commands determines the layering of each object on the canvas, so decide which shapes are supposed to appear on top of other shapes, and add those last.

Putting down some lines

Drawing lines is really a 6-step process (unless your lines are going to be 1px solid black, in which case you don’t need to bother with setting the stroke style or line width, because those are the default values).

1. Set the line width

2. Set the stroke style

3. Start a path

4. Plot the lines for the path

5. Draw the lines

6. End the path

You can set new line widths and stroke styles for as many lines as you want.  Here’s an example:

Making circles and arcs

A circle is simply an arc that goes all the way around.  The first thing you need in order to create one is the center point of the circle which will be expressed as x and y coordinates.  You then need to supply the radius (r), start angle (sa) and end angle (ea).  There is an optional “direction” flag (0 = clockwise, 1 = anticlockwise) but there is rarely much need for it.

The process for drawing the circles is similar to creating lines.  You specify a lineWidth, strokeStyle, and optional fillStyle if it is to be a filled circle.  You don’t need to bother with end-caps or line-joins unless you’re making an incomplete arc.  If the arc connects to other lines, then the precision of your angle in combination with the line-joins used on both components will affect the smoothness of the result.

Example – three unfilled circles:

The result may not have produced what you expected.  Can you guess why?  Although it probably shouldn’t, the pen stays down on the canvas the whole time unless you use a moveTo instruction.  This causes the pen to be temporarily lifted.

Let’s try that same thing again, but lifting the pen between creating each circle.

Hmm… it’s almost right, except that now there’s these weird lines inside the last two circles.  This happened because the move to point was the center of each circle.

To fix it, you need to move to the edge of the circle, so that means adjusting the x coordinate by 17.5px.  Let’s try it one more time.

Curious about where that 17.5px figure comes from?  It’s 0.75 times the radius amount plus half the line width.  This prevents any pixels from hanging out into space.  It feels unnatural to specify half a pixel, but it’s legal and it works.  Without that extra half pixel, you’ll get a small but noticeable bump on your line.

Drawing a cubic curve

Now let’s try something a little more advanced.  Cubic curves are a type of bezier curve.   They differ from quadratic bezier curves because they have two control points instead of just one, which makes them more complicated but also more refined.

To draw a cubic curve, you need to move the pen to the location where you want the curve to start, then use a bezierCurveTo instruction, where you will supply the x and y coordinates for the first control point (x0,y0),  the x and y coordinates for the second control point (x1,y1), and finally the x and y coordinates for the ending point of the line (x2,y2).  Example:

To draw a quadratic curve, simply don’t use the coordinates for the second control point.  Learning to draw bezier curves well is a topic for an entire tutorial on its own, but it’s still good to know the method used to create them.

Drawing a filled shape

So far we have only looked at simple line drawings.  To create a filled shape is not especially more complex.  For example, to create a filled circle, you can just do this:

So what is different there is the use of a fillStyle and then using a fill command.  That is really all that’s necessary.  Something that it’s also worth knowing is that you can apply the fill without using a stroke, but be aware that the stroke line width is still there even though you haven’t actually drawn it.

Filling with a gradient

Solid colors are fine, but sometimes you might want to use gradients, and that is possible in HTML5 canvas.  For a circle, as in the example, we’d normally use a radial gradient.  For other types of shapes, linear gradients are more popular.  Linear gradients are slightly more complicated since you also need to specify the direction (horizontal, vertical, diagonal) for the gradient to progress in.

Creating a radial gradient involves setting an inner circle, an outer circle, and color stop values to determine what colors the gradient will progress through.  For the example circle, which is quite small, we’ll need to set two circles inside it, starting with the same center point as the original circle.

You may recall that the center point for the circle was 50,25 and the radius was 20px.  The radius for our inner circle gradient should be set to 50,25 and it’s radius should be set to 5px.  The radius for the outer circle should be set to 50,25 and the radius can be anything between 6px and 20px.

Notice how even though the outer circle of the gradient is the same size as the circle to be filled, the stroke line of the circle is not overwritten by the fill color.

Applying a linear gradient

This time we’ll use a linear gradient, and also show what happens when the bounding area of the gradient fill is larger than the shape to be filled.

Notice that the fill, even though it is larger in size than the shape being filled and is rectangular, does not go outside the borders of the shape.  The gradient is also smoother and less eccentric than the radial gradient.

These techniques are by no means all you will have to learn in order to use the canvas to its full potential, but they are the basic techniques that every designer should know.  With these fundamental principles firmly understood, the learning curve for gaining mastery over the canvas will be a simple stroll from point to point, rather than a mad uphill scramble.

This post Basic HTML5 Canvas Methods Every Designer Should Know was written by Inspired Mag Team and first appearedon Inspired Magazine.