I need a function for my simple canvas in javascript:
The function determines where the mouse pointer is on the canvas and outputs the coordinates into two variables, pointerX, and pointerY.
The function constantly updates so the variables are always accurate.
Thank you for your time, and if you have any questions for details unmentioned, please reply below and I will respond. Thanks!
Take a look at MouseEvent
and here you go:
var canvas = document.querySelector("canvas");
var h1 = document.querySelector("h1");
canvas.addEventListener("mousemove", function(e){
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;
h1.innerText = `x:${x},y:${y}`
})
canvas{
border:solid;
}
<canvas width="100" height="100"></canvas>
<h1></h1>