HTML5 Canvas – The Basics

What is it?

Canvas is an element introduced in HTML5, written within the body tags. This element is just as other elements, for example a div, except that it renders it’s content with JavaScript. It can be used to render images, videos, animations and draw graphs.
The context of canvas can be 2d or 3d (WebGL). Canvas is supported in the all latest browsers. Click here to see more information about the browser compatibility.

How to use Canvas

As said, the canvas element is written within the body. You can choose to write this in a HTML file yourself or to render it by using JavaScript. Either way, you will have to set the context of your canvas in JavaScript. Here are two examples.

Example 1:
Canvas with width and height added in HTML and set context in JavaScript

   <!-- Canvas element with width and height set -->
   var canvas = document.getElementById('canvas'), // Get element (canvas) by id
        context = canvas.getContext('2d');          // Get rendering context

Example 2:
Canvas with width and height created and set context in JavaScript

    var canvas = document.createElement('canvas'), // Create canvas element
        context = canvas.getContext('2d');          // Get rendering context

    canvas.width = 400;     // Set canvas width
    canvas.height = 400;    // Set canvas height

    document.body.appendChild(canvas);  // Add canvas to body

Now the canvas has been created and the context is set to 2d, it’s ready to add images, videos, animations or to draw other things into it. Below you can read up on a few examples or drawing methods.

In the examples you will find a few parameters, namely:
– x: will be the horizontal position from the top left of the canvas
– y: the vertical position from the top left of the canvas
– width: the width of the rectangle
– height: the height of the rectangle

How to draw an image

There are different ways of drawing an image to the canvas, here is one of them.

   var anImage = new Image();
    anImage.src = 'images/image.png';

    anImage.onload = function() {
        context.drawImage(anImage, x, y);
    };

How to draw a line

    context.beginPath();
    context.moveTo(0, 0);
    context.lineTo(x, y);
    context.stroke();

How to draw a rectangle

    context.rect(x, y, width, height);
    context.fill();
    context.stroke();

How to draw a circle

    context.arc(x, y, radius, 0, Math.PI * 2);
    context.fill();
    context.stroke();

How to clear your canvas

    context.clearRect(x, y, width, height);
Portrait picture

Andy Haxby • Founder

Andy is the founder of Competa and FTSF. He is always looking to find ways to improve sustainability with software.