TenMinuteTutor

Coding, maths and art

Basic drawing

To create drawings with HTML5 canvas you will need two things:

  • A basic HTML page with a canvas element.
  • Javascript code to draw on the canvas.

For simple pages, these can be included in the same file. This makes things easier because you can open the combined file in a browser to view it.

Basic HTML page

Here is a bare-bones HTML page.

<!DOCTYPE HTML>
<html>
  <head>
  </head> 
  <body>
      canvas id="myCanvas" width="400" height="200</canvas>
  </body>
</html>

This page is empty except for a canvas element. The canvas is 400 pixels wide, by 200 pixels high. However, we haven’t drawn anything on it yet, so if you look at the page in a browser it will be blank.

Adding the Javascript

Here is some Javascript to draw a rectangle on the canvas:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.fillStyle = 'blue';
context.fillRect(100, 50, 200, 75);

Here is what it displays:

image

Looking at the Javascript

The first two lines of the Javascript are needed pretty much every time you use a canvas:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

We get a canvas object by calling getElementById. This is a standard DOM call to get a page object. The parameter we pass, myCanvas is the id we gave to the canvas in the HTML.

The second line obtains a “drawing context” for the canvas. This is the interface we need to actually draw things.

Now we get to the drawing code:

context.fillStyle = 'blue';
context.fillRect(100, 50, 200, 75);

First we set the fillStyle to ‘blue’. There are various ways to [[HTML5 canvas colours|set the colour]], the easiest is just to use the colour name (standard CSS names are supported).

Next, fillRect(x, y, width, height) defines a rectangle at position (x, y), which is (100, 50) in our case. The width of the rectangle is 200 pixels and the height is 75 pixels. All measurements are in pixels.

Putting it all together

For simple test pages, the HTML and Javascript can be combined in a single page. Save the following code as as HTML file and open it locally in your browser:

<!DOCTYPE HTML>
<html>
  <head>
  </head> 
  <body>
    <canvas id="myCanvas" width="400" height="200"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        
        context.fillStyle = 'blue';
        context.fillRect(100, 50, 200, 75);
    </script>
  </body>
</html>