Canvas How to - Get mouse clicked position








Question

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

Answer


<!--from  w w  w  . ja va  2 s . co m-->
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
#game {
   height:200px;
   width:200px;  
   background-color:gray;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var canvas = document.getElementById('game');
    var canvasX, canvasY;
    canvas.addEventListener('click', function(event) {
        canvasX = canvas.offsetLeft;
        canvasY = canvas.offsetTop;
        var eventX = event.clientX;
        var eventY = event.clientY;
        var relX = eventX - canvasX;
        var relY = eventY - canvasY;
        alert('X = ' + relX + ', Y = ' + relY);
    });
}//]]>  
</script>
</head>
<body><canvas id="game"></canvas>
</body>
</html>

The code above is rendered as follows: