Detect Mouse Coordinates on Canvas
In this exercise we are going to cover one of the most crucial aspects of making interactive canvas applications with JavaScript. We will demonstrate how to read or capture the user mouse coordinates upon specific events.
<!DOCTYPE html>
<html>
<head>
<style>
body{ margin:10px; background:#CCC; }
#my_canvas{ background:#FFF; border:#000 1px solid; }
</style>
<script>
function initCanvas(){
var ctx = document.getElementById('my_canvas').getContext('2d');
ctx.canvas.addEventListener('mousemove', function(event){
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
var status = document.getElementById('status');
status.innerHTML = mouseX+" | "+mouseY;
});
ctx.canvas.addEventListener('click', function(event){
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
// alert(mouseX+" | "+mouseY);
ctx.fillStyle = "orange";
ctx.fillRect(mouseX-15, mouseY-15, 30, 30);
});
}
window.addEventListener('load', function(event) {
initCanvas();
});
</script>
</head>
<body>
<canvas id="my_canvas" width="500" height="300"></canvas>
<h2 id="status">0 | 0</h2>
</body>
</html>