I'm writing an HTML5 canvas drawing app, and I need to be able to tell whether or not the left mouse button is pressed down during a mousemove event. On Chrome, this works:
if (event.which == 1) { <do stuff> }
But in FireFox, event.which always is 1, no matter whether or not the button is pressed.
How can I detect whether the mouse button is pressed during a mousemove event?
Actually, you can check
event.buttons
on Firefox which tells you if left button, right button or none are pressed. You will need an if-statement to differentiate with Chrome which doesn't haveevent.buttons
.In short, you can't. MDN, for example, explains:
If you want, you can set global
mousedown
andmouseup
handlers that set flags appropriately and then at any given point in time you can with relative degree of accuracy determine if/which mouse button is pressed.I use this pseudo-polyfill to avoid FireFox mouseMove problems:
I call it "pseudo" because, it forces me to check the button down while moving this way:
Instead of normal:
You should use a variable to hold the state of the mousedown. When you
mousedown
on the canvas set it to true, and when youmouseup
on the document set it to false..This way it will be cleared wherever you click..
Something like this
Demo at http://jsfiddle.net/gaby/8JbaX/