Dragging A Mouse Outside Of An HTML5 Canvas

JavaScript

15/05/2021


In an earlier post, I showed you how to create some basic drawing functionality using a canvas. However, there's one edge case that I didn't cover: dragging your mouse outside and back into the canvas.

Current issues

In the current implementation, the mouse release outside the canvas isn't being registered, i.e. isDrawing remains true. And on top of that, once the mouse returns to the canvas, our drawing reconnects with our previous drawing.

Bug dragging mouse back into canvas

Dragging mouse back into canvas

Mouse release

We are currently constraining the mouseup and mousedown events to the canvas itself. We should change this to the entire web page.

JAVASCRIPT
window.addEventListener("mousedown", startDrawing)
window.addEventListener("mouseup", stopDrawing)
canvas.addEventListener("mousemove", draw)

We can leave the last listener as is since we don't really care too much about mouse movements outside of the canvas.

Connecting points

To prevent the connecting bug I outlined earlier, we need to tell the canvas that we're starting a new drawing whenever the mouse enters the canvas.

There's a mouseover event that allows us to do that.

JAVASCRIPT
const enterCanvas = (event) => {
context.beginPath()
}
canvas.addEventListener("mouseover", enterCanvas)

The improved functionality can be viewed in this Codepen.


WRITTEN BY

Code and stuff