I am using HTML5 and want to know if the right mouse button or left mouse button is held down during a mouse move. The right mouse button has event.button = 2 for the right button. The left button has event.button = 0. During the mousemove, event.button = 0 always. I have supplied some sample code. What am I doing wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<title>demo on detecting mouse buttons</title>
<meta charset="utf-8"/>
<style>
#mycanvas{ border-style:solid; width:400px; height:400px; border-width:2px;}
</style>
<script type="text/javascript">
function detectDown(event)
{
var string = "Mouse Down, event.button = " +event.button;
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
context.clearRect(0,0,300,20);
context.fillText(string,0,10);
}
function detectMove(event)
{
var string = "Mouse Move, event.button = " +event.button;
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
context.clearRect(0,30,300,20);
context.fillText(string,0,40);
}
function detectUp(event)
{
var string = "Mouse Up, event.button = " +event.button;
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
context.clearRect(0,60,300,20);
context.fillText(string,0,70);
}
</script>
</head>
<!-- -->
<body>
<canvas id="mycanvas"onmousedown="detectDown(event)" onmouseup="detectUp(event)" onmousemove="detectMove(event)" >
</canvas>
</body>
</html>
The mouse move event is necessarily button-agnostic. It reports mouse movement, regardless of whether buttons are pressed or not. You need to create a flag on
mousedownthat tracks which button is down; reset it onmouseup.