Friday, November 2, 2012

Get HTML5 Canvas Click Co-ordinates

Click co-ordinates 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 amd opera does not support layerX, layerY, so we have to use offsetX, offsetY.
<meta charset="utf-8">
<script src="script.js"></script>
<canvas id="myCanvas"></canvas>
window.onload = function () {
var canvas = document.querySelector('#myCanvas'),
ctx = canvas.getContext("2d");

//draw something
ctx.fillStyle = "#000000";
ctx.strokeStyle = "#000000";

ctx.rect(100, 100, 300, 100); //x, y, width, height

//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);