This is what we are going to explain:
Our HTML5 canvas
If you watch carefully, when you draw on the canvas, your mouse is having a few interactions with the canvas. You point the muse down to start drawing and move it to draw and then point it up and out of the canvas to stop drawing. We have four mouse events to take care of.
The canvas specifics
You need to specify a few things for canvas like starting and stopping points, a flag that shows drawing status ( we always need flags with true-false status in our codes to make an indication of some actions that go on and of).
The draw function
Finally of course we need a drawing function that takes care of updating starting and ending points of drawing, changes the direction of drawing and takes care of colours as well.
Declare the canvas
I have made explanation for all lines. First get the canvas and add its specifics:
//get the canvas with its id
const canvas = document.querySelector('#draw');
//specify it is a 2d canvas using getContext method which returns a drawing <em>context</em> on the <em>canvas</em>
const ctx = canvas.getContext('2d');
//overwrite canvas's height and width to make it reflect the window size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//<em>lineJoin</em> property sets or returns the type of corner created, when two lines meet.The <em>lineCap</em> property sets or returns. The style of the end caps for a line. We make them both round and if you draw in the canvas you see what I mean.
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
//<em>lineWidth</em> property of the <em>Canvas</em> 2D API sets the thickness of lines in space units.
ctx.lineWidth = 100;
The end points
Then we need to declare a few things. Specifying the ending points of the drawing as 0,0 and specifying a variable for colour (hue) and also set the direction to true so we can draw straight and once we draw back we will change it in the draw function.
let lastX = 0; //x end point
let lastY = 0; // Y end point
`// Hue is a degree on the colour wheel from 0 to 360. 0 is red, 120 is green, 240 is blue. We use hsl which I explain later