<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script language="javascript">
function main(){
var canvas = document.getElementById("canvas");
canvas.addEventListener("mousemove", function(e){
if (!e) e = window.event;
var ctx = canvas.getContext("2d");
var x = e.offsetX;
var y = e.offsetY;
ctx.fillRect(x, y, 1, 1);
});
}
</script>
</head>
<body onload="main();">
<div style="width: 800px; height: 600px; -webkit-transform: scale(0.75,0.75); -moz-transform: scale(0.75,0.75)">
<canvas id="canvas" width="400px" height="400px" style="background-color: #cccccc;"></canvas>
</div>
</body>
</html>
Please consider the above quick and dirty example. Please notice that my canvas is contained by a div having a scale transform applied. The above code works perfectly on any webkit based browser. While moving the mouse it draws points on the canvas. Unfortunately it doesn't in Firefox as its event model does not support the offsetX / Y properties. How can I transform mouse coordinates from (perhaps) event.clientX (which is supported in firefox too) into canvas relative coordinates taking into account canvas position, transform etc? Thanks, Luca.
Try layerX, layerY
var x = (e.offsetX === undefined) ? e.layerX : e.offsetX;
var y = (e.offsetY === undefined) ? e.layerY : e.offsetY;
Unfortunately, Firefox layerX and layerY properties are differs from ones in other browsers. There are relative top-left corner of page, but not elemenet.
false, they are relative to the closest offsetParent including the element itself, just add "position:relative" to the element you want to use for coordenates.
Didn't work for me, but this worked stackoverflow.com/questions/12704686/…
Didn't work on FF 32.0.3 . layerX and layerY are absent from event.
layerX and offsetX are not the same, if the target is an inline element, the offset give the position of the cursor in the element, but return a layerX relative to his non-inline parent container.