HTML Canvas

The HTML <canvas> provides a rectangular area on a webpage on which graphics can be drawn. Canvas is used with javascript to create animated browser games.

Every canvas needs to have an id assigned to it. This will be used in the javascript code to access the canvas.

<canvas id="gameCanvas"></canvas>

 

Use the javascript getElementById() function to access the canvas id within the javascript code.

<script>
let canvas = document.getElementById("gameCanvas");
</script>

 

The physical width and height of the canvas element are set in the stylesheet. These values define how much physical space the canvas occupies on the webpage.

<style>
#gameCanvas
{
  outline:1px solid darkgrey;
  width:500px;
  height:500px;
}
</style>

 

The logical width and height of the canvas are defined using javascript. These are the values that are will be used in the game. If the canvas size does not match the style size, then the canvas drawing will be scaled. It is usually a good idea to ensure that the physical and logical sizes match. The physical size of the canvas can be got using the clientWidth and clientHeight properties of the javascript canvas. In these notes, the logical width and height will always be set to match the physical width and height, as shown below.

<script>
let canvas = document.getElementById("gameCanvas");
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
</script>

 

In order to draw onto the canvas, we need to assign a graphics context to it. This is done in javascript code using the getContext("2d") function. The code is implemented in the Game object constructor.

let ctx = canvas.getContext("2d");

 

Example of a minimal canvas, which draws a red square (Run Example)

<!-- Author: Derek O Reilly, Dundalk Institute of Technology, Ireland. -->

<!DOCTYPE html>
<html>
    <head>        
        <title>Course notes example code</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> #gameCanvas { /* the canvas styling usually does not change */ outline:1px solid darkgrey; width:500px; height:500px; } </style> </head> <body> <canvas id = "gameCanvas"></canvas> <script> let canvas = document.getElementById("gameCanvas"); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; let ctx = canvas.getContext("2d"); // draw something on the canvas ctx.fillStyle = "red"; ctx.fillRect(100, 100, 300, 300); </script> </body> </html>

Write code to draw four squares on the canvas, as shown here.