Getting started with canvas in JavaScript

Canvas is a special drawing field in the JavaScript browser. This field is created using the <canvas> tag, which should be given a width and height:

<canvas width="200" height="200"></canvas>

To work with this field in JavaScript, first we get a reference to this tag into some variable:

let canvas = document.querySelector('canvas');

Then the getContext method must be applied to this variable:

let canvas = document.querySelector('canvas'); let ctx = canvas.getContext('2d');

It can be simplified:

let ctx = document.querySelector('canvas').getContext('2d');

As a result, an object containing the so-called drawing context will be written to the ctx variable. All drawing will be done using the methods of this object. We will study them in the next lessons.

enru