How to draw with mouse in HTML 5 canvas ?
The canvas element by default has some properties such as padding etc.(can be changed styles). Hence, properties offsetTop and offsetLeft are used to retrieve the position of the canvas, relative to its offsetParent (closest ancestor element of the canvas in the DOM). By subtracting these values from event.clientX and event.clientY, we can reposition the starting point of the drawing to the tip of the cursor. In the function sketch(), we use the following in-built methods to add functionality.
- beginPath(): Starts a new path, every time left mouse button is clicked.
- lineWidth: Sets the width of the line that will be drawn.
- strokeStyle: In this regard, we use it to set the color of the line to black. This attribute can be changed to produce lines of different colors.
- moveTo(): The Starting position of the path moves to the specified coordinates on the canvas.
- lineTo(): Creates a line to from the said position to the coordinates specified.
- stroke(): Adds stroke to the line created. Without this, the line will not be visible.