Today I am very excited! I finished the first stable iteration of a JavaScript game that I have been working on for a few weeks now.
But That Probably Isn’t Why You’re Here
Basically we need a way to track the coordinates in real time as the mouse moves around inside the browser using JavaScript.
Say we had some function in our JavaScript file called “setHoverCoordinates(positionX, positionY)” and we also had a canvas element identified as ‘c-container’.
We could use the following code snippet to get the coordinates of the mouse when the mouse entered the space of the canvas element:
document.getElementById('c-container').addEventListener('mousemove', e => { this.setHoverCoordinates(e.clientX, e.clientY); })
The event that is triggered by the mouse moving over the canvas element will contain the properties “clientX” and “clientY” which we can use to reference the position. Remember that (0, 0) exists in t he top left corner.
So that’s ‘mousemove’…
I was under the assumption that the same logic would easily transfer to the ‘touchmove’ event.
Turns out the events fired by the finger dragging on a touchscreen device do indeed have the properties “clientX” and “clientY”, but I was unable to get continuous events to update the variables in my setHoverCoordinates function.
Here is how I was able to get the same behavior as ‘mousmove’ for a touchscreen ‘touchmove’ event:
document.addEventListener('touchmove', e => { this.setHoverCoordinates(e.targetTouches[0].pageX, e.targetTouches[0].pageY); })
The events triggered contain an array of objects, “targetTouches”, where each object contains the properties “pageX” and “pageY”. The first index gives use the information we seek.
I hope this saves you time in your quest to develop similar functionalities for mouse-hovering and touchscreen-dragging -ish events.