The basic’s of the canvas element

Amanda de Rijk

<canvas> is an HTML element which can be used to draw graphics on a website. This element uses scripting, like in this example JavaScript. This element can be used to draw graphs, make photo compositions or animations for example. In this blog I’ll explain how to use the canvas element and how to get a basic shape on there.

The use of the canvas element is pretty easy. You only need basic knowledge of HTML and JavaScript. The canvas has a default width of 300px and a default height of 150px. You can, of course change these sizes with the height and width settings. If you, for example, want a canvas with a height of 500px and a width of 1000px your HTML will look like this:

<canvas id="game" height="500" width="1000">
    fall back content

As you might see I have placed some fall back content inside the canvas element. This is because not all older browsers support the canvas element. So if its not showing it will show whatever is in the canvas element.

Next you’re going to need Javascript to ‘draw’ on the canvas.

The canvas element only supports one basic shape, the rectangle. All other shapes must be created while connecting paths, points and lists with lines. Since this is more complex We’re going to focus on the rectangle for now. You can use 3 functions to draw rectangle on the canvas:

Draw a filled rectangle.

fillRect(x, y, width, height)

Draw a rectangular outline.

strokeRect(x, y, width, height)

Clear the specified rectangular area, making it fully transparent.

clearRect(x, y, width, height)

Each of these three functions takes the same parameters:
– X and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle
– Width and height provide the rectangle’s size

While drawing this rectangle your JavaScript file will look like this:

function draw() {
    var canvas = document.getElementById('canvas'),
    example = canvas.getContext('2d');




you might also like