CODING ACADEMY

View Original

Drawing Shapes using HTML5 Canvas - Part 1: Creating the Canvas

In this series of tutorials I will be showing you how to use the HTML5 canvas to draw basic shapes.

Over the last few months I have had the need to use the HTML5 canvas on a number of projects. This simple, yet powerful, feature is easy to use and very effective.

HOW TO CREATE A HTML5 CANVAS

Before we draw a rectangle we must first create the canvas element. There is a HTML <canvas> element. We set the width and height of the element within the tag rather than using CSS. Although CSS can be used you may find it better to avoid resolution conflicts by setting the width and height within the canvas element. We can also give the element an ID as follows:

See this content in the original post

Line 10: The canvas is given an id of myCanvas and the width is set at 500 pixels and the height at 400 pixels.

DID YOU KNOW…

If you do not declare a width and height for your canvas then a default width and height will be used. Currently this is:

width: 300 pixels
height: 150 pixels

If the page above is viewed the the canvas will not be ‘seen’ as it will be the default white background on the white browser page. You can use CSS to style the canvas as you would any other HTML element.

In the example below I have drawn a 1 pixel solid border around the canvas.

See this content in the original post

DECLARING THE CANVAS CONTEXT

The canvas element can be used for different rendering contexts. In this series of tutorials I will focus on the most common which is the 2D context.

See this content in the original post

Line 14: we retrieve the canvas node from the DOM (Document Object Model)

Line 15: we declare the canvas context as 2D

HOW TO CHECK IF A BROWSER SUPPORTS THE HTML5 CANVAS

Not all browsers support the HTML5 canvas so it would be useful to check if this is the case and present fallback content if required.

See this content in the original post

A SIMPLE EXAMPLE

The last step is to draw some content within the canvas. In this simple example we will draw a rectangle:

See this content in the original post

Line 14: we set up a function to contain the canvas drawing code

Line 18: we draw a simple rectangle

Line 27: we call the rectangle function so that the canvas is created and the rectangle drawn.

This will produce the following:

See this content in the original post