Canvas How to - Get mouse position in clicked event








Question

We would like to know how to get mouse position in clicked event.

Answer


<!--  w w w  .ja  va 2s  .c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
function test(e){
    var coords = getxy(e,this);
    document.getElementById('cords').innerHTML = 'X '+coords.x+' | Y '+coords.y;
}
function getxy(event,el){
    canvasX = event.pageX - el.offsetLeft,
    canvasY = event.pageY - el.offsetTop;
    return {x:canvasX, y:canvasY}
}
var c = document.getElementById('canvas'),
    ctx = c.getContext('2d');
    var img = new Image();
    img.src = 'http://www.java2s.com/style/download.png';
    img.onload = function(){
        ctx.drawImage(img,10,10);
    }
    c.addEventListener('click',test,false);
}
</script>
</head>
<body>
  <div id="cords"></div>
  <canvas id="canvas" width="600" height="300"
          style="position: absolute; width: 600px; height: 300px; border: 1px solid red;">
    </canvas>
</body>
</html>

The code above is rendered as follows: