Canvas How to - Handle Mouse move event








Question

We would like to know how to handle Mouse move event.

Answer


<!--  w  w w  . j ava2  s. c  o  m-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.5.js'></script>
<style type='text/css'>
canvas {
  background: gray;
  border: 2px groove;
}

span {
  display: block;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
$(function(){
    var canvas = $('canvas');
    canvas.mousemove(function(e){
        var pageCrds = '('+ e.pageX +', '+ e.pageY +')',
            clientCrds = '('+ e.clientX +', '+ e.clientY +')';
        $('span:first').text('(e.pageX, e.pageY) - '+ pageCrds);    
        $('span:last').text('(e.clientX, e.clientY) - '+ clientCrds);
    });
    var arr = [];
    canvas.click(function(e) {
        arr.unshift($('span.first').text());
        console.log(arr);
    });
});//]]>  
</script>
</head>
<body>
  <canvas width="300" height="225"></canvas>
  <span class="first">Move the mouse over the div.</span>
  <span></span>
</body>
</html>

The code above is rendered as follows: