Getting Started with HTML5 Canvas

Johnny Simpson - Mar 9 '22 - - Dev Community

HTML canvas is the easiest way to create graphics in Javascript and HTML. You may see it also written as HTML5 Canvas, as it is strongly associated with the shift to HTML5.

HTML Canvas can be hard to get the hang of. If you agree, you're not alone. So in this guide let's go through the basics of HTML canvas, and how you can use it.

How to use HTML5 Canvas

To start with HTML5 Canvas, we need to create a <canvas> element. This is just an empty tag which will contain the graphic produced by our Javascript. In HTML, we can create a canvas by writing the following:

<canvas id="myCanvas" width="400" height="200"></canvas> 
Enter fullscreen mode Exit fullscreen mode

You may often see canvas with predefined width and height, which is useful if the graphic we're producing has to have a certain size. You could set your canvas to be of width and height 100%, too.

That's all you need to do on the HTML side of things. Let's look at how we can initiate a basic canvas which we can start to produce graphics on.

Creating a HTML5 Canvas with Javascript

The next thing we have to do to produce our canvas is to select our canvas element, and apply a context to it.

Applying a context to our HTML5 Canvas with getContext()
Canvas elements can have a context added to them - which can be one of the following:

  • 2d - a 2 dimensional context for rendering 2d graphics on.
  • webgl - a 3 dimensional context for rendering 3d objects on.
  • bitmaprenderer - only allows us to replace the canvas context with something that is a BitImage.

Although all of these are useful, for most canvas work, we use 2d. So let's start by selecting our canvas element, and applying the correct context:

let myCanvas = document.getElementById('myCanvas');

// Set the context of our canvas
let context = myCanvas.getContext('2d');
Enter fullscreen mode Exit fullscreen mode

Above, we now have a variable, context, which we can use to draw graphics on our canvas. Although I've called this variable context, it is common to see it named ctx instead.

Remember Javascript Order

If you are having trouble getting this to work, make sure your Javascript is after your <canvas> element. The HTML element needs to exist before we can select it!

Drawing on our canvas

Now we have our context, we can start to draw on it. HTML canvas has a number of different ways to draw. Let's look at a basic example - creating a rectangle.

let myCanvas = document.getElementById('myCanvas');

// Set the context of our canvas
let context = myCanvas.getContext('2d');

// Begin drawing something on the context
context.beginPath();
// Draw a rectangle using the rect() function
context.rect(188, 50, 200, 100);

// Fill our rectangle
context.fillStyle = '#13caa7';
context.fill();

// Add a border to our rectangle
context.lineWidth = 5;
context.strokeStyle = 'white';
context.stroke();

// Finish our rectangle
context.closePath();
Enter fullscreen mode Exit fullscreen mode

Output of this code:

HTML5 Canvas Example

As you can see, HTML canvas drawing can become quite verbose quite quickly. Let's break down the code section by section after creating our context:

context.beginPath()
We begin any new shape or drawing on a canvas with beginPath(). This lets us split out the information on one shape, versus the next.

context.rect(10, 10, 100, 120)
This is a standard shape function, the arguments of which are x, y, width, height. The above code then creates a rectangle 10px from the top and 10px from the left, of width 100px and height 120px.

context.fillStyle, context.fill()
The first line, fillStyle, sets the color, and then fill the shape itself with the function fill().

context.lineWidth, strokeStyle, stroke()
These should look familiar to the last section - we set the pixel width of the border with lineWidth, then the color with strokeWidth, and action the stroke with stroke().

context.closePath()
Our rectangle is now done - we finish it off by using the closePath() function. Now that we've closed our path, we are free to create more shapes if we like.

Drawing Multiple Shapes with HTML5 Canvas

Since we're using Javascript, we can programmatically draw shapes with canvas. For example, we can use a while loop to draw many rectangles, all beside each other:
Example of HTML5 Canvas

The code for this follows the same concepts as we followed before - the only difference is that we are using a while() loop to reiteratively draw more rectangles until the canvas is full:

Using a while loop in HTML5 Canvas:

let myCanvas = document.getElementById('myCanvas');

// Set the context of our canvas
let context = myCanvas.getContext('2d');

// Draw a rectangle using the rect() function
let startX = 10;
let startY = 10;
let rectWidth = 100;
let rectHeight = 100;

while(startY < newCanvas.height) {
    // Begin drawing something on the context
    context.beginPath();
    // Draw our canvas
    context.rect(startX, startY, rectWidth, rectHeight);
    // Fill our rectangle
    context.fillStyle = '#13caa7';
    context.fill();

    // Add a border to our rectangle
    context.lineWidth = 5;
    context.strokeStyle = 'white';
    context.stroke();

    // Finish our rectangle
    context.closePath();

    startX += rectWidth + 10;
    console.log(startX, startY, newCanvas.width, newCanvas.height)
    if(startX > newCanvas.width - 100) {
        startX = 10;
        startY += rectHeight + 10;
    }
    if(startY > newCanvas.height - 100) {
        startX = newCanvas.width + 50;
        startY = newCanvas.height + 50;
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this introduction, we've looked at how HTML5 canvas can be created, and how you can draw basic shapes onto it. We've covered how you can reiteratively draw on the canvas through Javascript, by using a while loop. Using this as a base, you'll be able to experiment and try out even more. I hope you've enjoyed this article.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .