Click coordinates for HTML5 canvas element can be obtained using both layerX
, layerY
property or offsetX
, offsetY
of the click
event. Firefox does not support offsetX
, offsetY
so we have to use layerX
, layerY
and opera does not support layerX
, layerY
, so we have to use offsetX
, offsetY
.
<html>
<head>
<meta charset="utf-8">
<script src="script.js"></script>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
// script.js
window.onload = function () {
var canvas = document.querySelector("#myCanvas"),
ctx = canvas.getContext("2d");
// draw something
ctx.fillStyle = "#000000";
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.rect(100, 100, 300, 100); // x, y, width, height
ctx.fill();
ctx.stroke();
ctx.closePath();
// listen for click event
canvas.addEventListener("click", function (e) {
var cX, // will contain clicked x co-ordinate
cY; // will contain clicked y y co-ordinate
if (e.offsetX == null) { // in case of Firefox
cX = e.layerX;
cY = e.layerY;
} else { // in case of Opera layerX does not work, use offsetX instead
cX = e.offsetX;
cY = e.offsetY;
}
console.log("clicked at: " + cX + " " + cY);
}, true);
}