Getting Started: 2D Canvas Application

An Intro to 2d Canvas

Zak Frisch
WDstack
12 min readFeb 22, 2017

--

Setting up our Canvas

We start out by creating a Canvas element within our Web Page

HTML:

Note: The text between Canvas’ open and closing tags is only rendered if the HTML5 Canvas is not supported. This is something we get for free so please don’t overthink it.

Now we setup our variables in our code so that we can reach out to the Canvas and manipulate it.

JavaScript:

For those new to Canvas this is probably the oddest thing in the world. For most everything else in the DOM you can find the methods that correspond to manipulating that element upon that element. This is a little different with Canvas. Why?

Under the Hood

About a decade ago my best friend was driving around a Black 1996 Buick LeSabre with a giant Danzig skull on the front.

Unfortunately no pictures remain before it finished devouring its quota of souls, erupted into flames, and was swallowed up by the abyss. (probably)

The 1996 Buick LeSabre and all GM cars built at the time came with two keys. A round key to open the doors, and a square key for the ignition. I know, I know. It probably sounds nuts to some of the younger folks, but the system worked well and had its advantages. Digressing to the point, Canvas’ two step setup works the same way.

You’ll notice that the variablectx (context) is a reference to the getContext method call on the Canvas element and it passes in the string “2d” as a parameter.

If that sounds confusing and verbose, that’s okay! Let’s break it down further and show an example of what’s happening behind the scenes:

Keep in mind that the above is an example of what the canvas.getContext function looks like. It is not a verbatim representation.

We can’t see the actual code because it is native to the Browser and hidden from view. In addition, the real getContext function takes an additional Object parameter that I will not be delving into for the duration of this article. If you would like you can certainly look at the MDN Article.

To recap, what happens is this:

  1. We grab the Canvas Element
  2. We get the Context Object by calling a method on the Canvas Element.
  3. Based on the context name we pass as a parameter, the method returns a specific Object.

Starting The Engine

If grabbing the Canvas element and its Context are opening the door and putting the key in the ignition, requestAnimationFrame can be considered starting the engine.

An Example:

This may be a little confusing if you have never seen it before. I have tried to comment it to make it a little easier to understand, but I will admit a bit of frustration with this concept initially as well, so I will try to explain this a different way.

The function above is, simply put, a function being invoked(draw) that proceeds to call itself over and over. It could be rewritten as this:

This is what’s known as Recursion. I’ve written more about this previously here.

Recursion in JavaScript is, simply put, the ability to call a function from within itself.

So if the above two snippets are fundamentally the same, what do we get out of using requestAnimationFrame that we don’t get out of a plain recursive function call?

The answer is in the name. Whatever function you pass the requestAnimationFrame method it will send a request to the Browser — “Can you process this?” and if the Browser is free to do so, it will. The MDN illustrates this in its own definition:

The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.

This will call the function only once, so to continuously ask the browser “Can you process this?” we use recursion to continuously call our function using requestAnimationFrame. The MDN explains this as well:

You should call this method whenever you’re ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation. The callback rate may be reduced to a lower rate when running in background tabs or in hidden <iframe>s in order to improve performance and battery life.

It is important to note, as specified above, that using requestAnimationFrame will typically pause a Canvas Application when it is not the currently selected Tab in modern browsers.

To illustrate this let’s go through a quick example. Keep in mind, we will go over the fillRect() method in the next section. What you should focus on is the architecture.

Shapes, Paths, and Colors

The Canvas 2d Context has a number of methods built in to assist with the creation of images. Since this is an introduction, and a quick one at that, we will only go through a few of the most basic shapes and the different methods to draw them.

Our first shape, the Rectangle:

Example 1 —

Example 2 —

Example 3 —

Example 4 —

Paths

In the above code you’ll notice the last two rectangles are drawn using “Paths”. If you haven’t heard that term before it may be a little confusing. Within Canvas and other drawing applications, a Path is a set of instructions that is collected together and then rendered all at once to a view. Basically, we can declare several shapes(and lines)and then draw them all at the same time. This is the basic principle that will allow you to draw complex shapes.

Knowing this, the above example of diagonal cubes could be refactored into two paths(one for outlined boxes, and one for filled):

Fill and Stroke

The context has two methods that we use frequently. They are the following:

These two methods are used to draw the preceding path. The context.fill method will fill in the preceding path with a color. The context.stroke method will outline the preceding path with a color. As seen in the examples above, the default color is black. Let’s quickly go over how to change that!

Colors

Colors are an important part of an image, wouldn’t you say? So far we‘ve been drawing to the screen with the default color, black, but that’s pretty boring. Fortunately, it’s quite easy to change this. Unfortunately(as with a few things in Canvas) the wording isn’t quite that intuitive. You may think that the properties to adjust the coloring would be named something likestrokeColor and fillColor but, in fact, the properties we need to adjust arestrokeStyle and fillStyle.

An Example:

In the above example you can see us use fillStyle and strokeStyle to render different colors to the screen. You will also notice that we used several different formats for setting the color property including:

  • RGB:rgb(0,0,0)
  • Hex:#000 or #FF0000
  • Safe Web Colors(HTML colors): blue , green , etc...

Additionally these other formats will also work:

  • RGBA: rgba(0,0,0,.3)
  • HSL: hsl(120,100%,50%)
  • HSLA: hsl(120,100%,50%,.3)

Circles

The second most commonly used shape is probably a circle. It is a bit more complicated than a rectangle because instead of simply saying “Hey you, Canvas, draw a circle!” we have to tell our Canvas exactly how to do that with a few more parameters.

To create a circle we create an arc. The arc method looks like this:

counterclockwise/clockwise is an optional Boolean (true or false) parameter and if it isn't explicitly declared it is considered false.

Example 1 —

There are two important concepts when it comes to arcs. The first is that with this statement:

the X and Y parameters are the center point of the arc. That means the above code renders the circle around the point 0,0 and we’re left with three quarters of our circle outside of the Canvas view.

This is as much as we can see of our circle

It’s important to remember this when positioning elements using arc Once you start building your own HTML5 Canvas Apps it can lead to quite a few headaches if you forget that the x and y coordinates are in relation to a center point.

The second important concept is that of the parameters Start Angle and End Angle. Keep in mind, it is important, but it is also entirely possible to build cool HTML5 Applications without knowing anything other than how to make a circle. The concepts involved are a little trickier, however, so I moved the examples and explanations off into another post. I recommend taking a look of course, but it isn’t necessary. You can find that article here:

Simple Drawing

It is important to be able to draw millions of different shapes. Unfortunately that means there are far too many to simply add as methods to the canvas context. There may come a time when you need more than just simple rectangles and arcs, and when that time arrives you’re going to need to know how to create your own paths.

Path Methods

If you’ve been following along you will have seen Paths mentioned several times. To reiterate:

a Path is a set of instructions that is collected together and then rendered all at once to a view

The basic methods of drawing Paths are fairly straight-forward:

beginPathand closePath are self-explanatory. As stated above though, it is important to know that closePath will try to close a shape if it’s open. In the following example we have 2/3’s of a triangle drawn:

If we want to close the shape we could draw a line connecting the last two points, however, we could simply call closePath as a much simpler solution.

The other two methods are moveTo and lineTo. You can think of these methods as though you are a Professional drawing on an actual Canvas.

The image above is synonymous with moveTo because the artist is moving the position of the pencil without touching the canvas. They are simply moving their hand in order to draw the next line.

lineTo in much more obvious fashion, looks like this:

moveTo and lineTo example:

There are other, more advanced methods, of course. These include:

It is good to know these exist, but these are a little more complex so we won’t be going into these today. If you would like more information you can find it at the MDN Canvas Context site.

Rendering Font

One subject that we haven’t gone over is that of rendering text inside of a Canvas Application.

We do so using the following methods:

fillText and strokeText either fill the text with color, or outline the text with color. These are very similar to the fill and stroke methods we’ve covered previously, so it shouldn’t be any surprise.

font is a String Property. The string that is set determines the font output for the fillText and strokeText methods. The string must be formatted in the following order:

context.font= ”font-style font-variant font-weight font-size font-family”;

However the only required fields are font-size and font-family. The following strings are valid:

Order is still important. The following strings are invalid:

A working demo:

For more information on the different parameters allowed in the font property, please look over this article at w3 Schools

There are a lot more things that we could get into regarding HTML5 Canvas, but I think at this point it is safe to say that you should have a grasp of the basics which is what we are going for here.

I will be releasing articles in the future regarding Canvas DPI, Caching, and several other one-off topics, and I’ll be certain to update this article when those are completed.

Please see the resources below with any questions!

Resources

html5canvastutorials.com

--

--