The canvas element is used to draw custom graphics on a webpage, and can also be used to animate images. html games are often created using the canvas element, as you can create custom graphics and animate characters or run mathematical calculations. For example, you could make a character image move around the canvas and interact with other graphics or objects also drawn on the canvas.
<canvas id="canvas" width="300" height="300"></canvas>
Before being able to draw graphics onto a canvas we first need to get the context. The context is the object that allows us to draw on, imagine the canvas element being the frame and the context being the paper that we draw on. First we need to get the canvas element by using the ‘getElementById’ method and passing in the value of the id given in the code above. The context is taken from the canvas element by using the ‘getContext’ method. We pass in the value of “2d” into the ‘getContext’ method as we want to draw 2D graphics onto the canvas. To draw 3D geometries onto a html canvas we would pass in the value ‘opengl’ but that is not covered in this post.
var c = document.getElementById("canvas"); var ctx = c.getContext("2d");
When using the context you must set the colour before drawing anything, such as basic shapes. You can draw basic shapes, such as: squares, rectangles, circles, etc. However, you must set the colour before drawing the shape, so a bit like putting the brush into the right colour paint before putting the brush onto the paper. The below code shows setting the colour, or ‘fillStyle’, and then drawing a rectangle onto the canvas. The ‘fillRect’ method takes four parameters, the starting x and y location then the ending x and y location. The x and y origin, the 0,0 point, starts at the top left of the canvas. In our canvas the x y location 300,300 will be the bottom right of the canvas. So the below code drawing a rectangle that colours the entire canvas in the colour black.
ctx.fillStyle = "black"; ctx.fillRect(0, 0, 300, 300);
We can then add shapes on top of previously drawn shapes. This works the same as painting, if we draw a rectangle after another one then the last shape will be drawn over the top of the previously drawn shapes or paint. The below code will drawn a blue rectangle over the top of the previously drawn black rectangle. The top left coordinate will be 75,75 and the bottom right coordinate of the blue rectangle will be 150,150. This will put the blue rectangle in the middle of the canvas.
ctx.fillStyle = "blue"; ctx.fillRect(75, 75, 150, 150);
Similar to CSS colours there are predefined colour names, rgb colours, and hex colours. The below code shows how to set the ‘fillStyle’ of the context using an rgb colour and using a hexadecimal colour. These methods can be used to change the current colour to a more precide or custom colour.
ctx.fillStyle = "rgb(0, 0, 255)"; ctx.fillStyle = "#0000BB";