Intro to Javascript Canvas

Nora LC
2 min readJul 8, 2021
source

Canvas is an HTML5 element that is used to draw graphics on a web page. Like Wikipedia defines it — It allows dynamic, scriptable rendering of 2D shapes and bitmap images. It is a low-level, procedural model that updates a bitmap and does not have a built-in scene graph.

The Canvaselement can be created in order to solve various web development problems. The following are few examples:

  • Visual enhancements (like creating a logo)
  • Security/Fingerprinting
  • Creating art (for more on that, go to the source link of the above image)
  • Creating animations

— Let’s now create a 2D square canvas with a rectangle shape on it —

Construct a Canvas

let canv = document.creatElement('canvas');

Make it Visible

In order to make it visible, its height and weight must be specified.

canv.height = 500;
canv.width = 500;

Start a Context

Just like in art, a canvas defaults to an empty surface and the context is the paint.

let context = canv.getContext('2d')

Fill the context

The first two parameters are the locations to start drawing. The third is the width and the last is the height.

context.fillRect(20, 20, 150, 100)

Add it to the DOM

This adds the canvas to the DOM just like appending any other classic HTML element.

document.appendChild(canv);

That’s it. We have now created a basic example of a canvas. Hope this was useful.

--

--