Using the HTML5 canvas to draw shapes

The code below shows how to use the HTML5 canvas and JavaScript in a webpage to draw objects. In this example, the object will be a simple rectangle shape inside a canvas with a grey border. The rectangle will be filled with red and have a blue border. It will look like this:

Screen Shot 2015-05-04 at 7.53.26 pm

You can use the canvas for drawings, animations, and even games. Watch the video below to see how to create a canvas and draw a rectangle shape, then scroll down to see the code.

Check out the sample code below. You can view all the different HTML colour codes that you can use here.

<!DOCTYPE html>
 <title>Simple canvas with rectangle drawing</title>
 background-color: white;
 border: 1px solid black;
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.fillStyle = "red";
 ctx.strokeStyle = "blue";
 <canvas id="myCanvas" width="200" height="100">

Next tutorial: Drawing lines using the HTML5 canvas element