I am attempting to locate the coordinates of the mouse on a canvas element of an HTML5 page.
I create the canvas to be a certain height and width, for example 700x700. W
The mouse coordinates are in display pixels. To convert that to canvas coordinates, you'll need to scale them accordingly.
One way of doing this is:
var canvasX = mouseX * canvas.width / canvas.clientWidth;
var canvasY = mouseY * canvas.height / canvas.clientHeight;
as shown in this example:
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = 700;
canvas.height = 700;
var ctx = 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("coords");
// scale mouse coordinates to canvas coordinates
var canvasX = mouseX * canvas.width / canvas.clientWidth;
var canvasY = mouseY * canvas.height / canvas.clientHeight;
status.innerHTML = mouseX+" | "+mouseY+"<br>"+canvasX+" | "+canvasY;
});
canvas {
width:250px;
height:250px;
background-color:#f0f;
}
<div id="coords">??? | ???<br>??? | ???</div>