How to Draw Shapes on the HTML Canvas

By: O. Wolfson

Draw shapes in the browser using the Canvas API.

Get the HTML for this app here.

The canvas element can be referenced to perform drawing functions. From w3schools: “The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. The canvas element is only a container for graphics. You must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.”

Create a canvas element in HTML.

<canvas id="canvas" width="400px" height="400px"></canvas>

Next create a reference to the canvas element in our javascript, here using const canvas = document.getElementById( ‘canvas’ ).

From the canvas reference we must create a drawing context. Use: const ctx = canvas.getContext(“2d”). What is a drawing context? Here’s what the HTML5 Specification say’s about getContext : “Returns an object that exposes an API for drawing on the canvas. The first argument specifies the desired API. Subsequent arguments are handled by that API.” We are using the “2d” drawing API. The 2d drawing context gives us some functions we can use to draw 2d shapes into the canvas.

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

The first 2d context function that we use is fillRect( ), which fills in a rectangle of a specified size and location within the canvas. Assigning ‘white’ to the fillStyle sets the color for this fill.

ctx.fillStyle = 'white'
ctx.fillRect(0,0, canvas.width, canvas.height);</code>

Next, we again call fillRect. This time in a for loop, creating several rectangles. We assign random values to the parameters to get diverse position and colors.

for (let i = 0; i < 100; i++) {
   const r = Math.random() * 255;
   const g = Math.random() * 255;
   const b = Math.random() * 255;
   ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
   ctx.fillRect(Math.random() * 400, Math.random() * 400, 50, 50);

Next we draw a line by calling several functions. Start the path by calling beginPath( ), and use moveTo( ) to specify the path’s beginning coordinate. Inside a for loop we call lineTo( ) to create several line segments to random coordinates on the canvas. Finally we call stroke( ) to color the path.

   ctx.moveTo(Math.random() * 400, Math.random() * 400);
   for (let i = 0; i < 100; i++) {
      ctx.lineTo(Math.random() * 400, Math.random() * 400);