I have simple Javascript code, similar to this one:
var mouseIsDown = false;
...
function canvasMouseDown(e) {
...
mouseIsDown = true;
}
function canvasMouseUp(e) {
mouseIsDown = false;
}
function canvasMouseMove(e) {
if (mouseIsDown) {
...
}
}
with implemention my own user interface for tranformations (translations, scalings and rotations) with canvas.
Such implementation within canvasMouseMove() function check mouseIsDown variable. All works fine if user does not release mouse button when the cursor/pointer is outside of the canvas element. If that happen, the variable mouseIsDown stays true and is not turned off by canvasMouseUp function.
What is easy fix or solution in pure JavaScript (no jQuery) for this issue?
If you want to catch the
mouseupevent somewhere else in the document, you might add an event handler for this to thedocumentelement. Note that this won’t react onmouseupevents outside the viewport, so you might want to fire also when the mouse enters the viewport again without a pressed button.If you want to catch the mouse leaving your canvas element, it gets a bit more complicated. While IE knows a
mouseleaveevent, the standard DOM has amouseoutevent that also fires when a descendant of your element is left (although canvas usually has no child elements). Read more on that at quirksmode.org.I have created a fiddle to demonstrate the behaviour (works only with W3 DOM). You might try to change
documentelementtobody. In Opera, themouseuplistener on<html>event detectsmouseupevents outside the document when the “drag” began inside it – I do not know whether that is standard behaviour.