Drawing On An HTML Canvas Using A Mouse
JavaScript
08/05/2021
Once you understand the basics of an HTML canvas, adding draw functionality isn't that difficult. But don't worry, I'll still show you how to do it step by step even if it seems out of reach to you. 🙌
Mouse actions
One part of the equation is knowing how to respond to user input. When drawing, there are only 3 possible actions:
- Pressing a mouse button
- Moving the mouse
- Releasing the mouse button
Consequently, we will implement 3 listeners 👂 that will each listen to one of these actions.
canvas.addEventListener("mousedown", startDrawing)canvas.addEventListener("mouseup", stopDrawing)canvas.addEventListener("mousemove", draw)
I've already added the associated functions which I'm about to go through.
Track state
Let's first get the issue of state out of the way, specifically when the drawing should be done. Think about it... 🤔
The user might move his mouse and not intend to draw. For that, we need to know if any mouse movements by the user should be committed to the canvas. We can do that with the help of a simple boolean variable.
let isDrawing = false
Start drawing
The user clicks on a mouse button 🖱 which triggers startDrawing
. We now know that the user intends to draw something, so we set isDrawing
to true
.
const startDrawing = (event) => { isDrawing = true context.beginPath() context.moveTo(event.clientX, event.clientY)}
We then tell the context that we are starting to draw with beginPath
and we add our first point with moveTo
. The x and y coordinates of the point can be retrieved through the event object.
Moving the mouse
As I mentioned in the state section, we need to know whether the user intends to draw when he's moving the mouse. So for that, we simply quit 🚪 the function early if isDrawing
is set to false
.
const draw = (event) => { if (!isDrawing) return context.lineTo(event.clientX, event.clientY) context.stroke()}
If drawing was the intention, we add a new point to the canvas context with lineTo
. Then we make the distance between this point and the previous one visible with stroke
.
Note that the previous point will either come from startDrawing
at the very start or draw
afterwards.
Stop drawing
Last but not least, 😌 when the user releases the mouse button, we simply set isDrawing
back to false.
const stopDrawing = () => { isDrawing = false}
You can inspect the functioning code in my Codepen.