How to Draw Shapes on the HTML Canvas
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
Create a canvas element in HTML.
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.
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.
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.
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.
Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.