I want to know how to track the position of the mouse on X-axis on the screen. Based on limited knowledge of Java/Processing, it is something similar to mouseX in Java. In addition, I want to rotate an image element based on the position of the mouse on X-axis. It would be nice to receive some pieces of advice.
Asked
Active
Viewed 1,070 times
-1
-
Check this out https://stackoverflow.com/questions/7790725/javascript-track-mouse-position – Karan Tewari Jun 03 '19 at 09:31
-
https://stackoverflow.com/questions/7790725/javascript-track-mouse-position – SandOfTime Jun 03 '19 at 09:31
2 Answers
0
a popular library/framework that is similar to Processing is P5.js (developed by the same people but for javascript) which can handle this for you
but in vanilla javascript, you would need an event listener
var mouse = {
x: undefined,
y:undefined
};
window.addEventListener("mousemove", function(event) {
mouse.x = event.x;
mouse.y = event.y;
});
what this does is listens for a mouse movement, and then records it to an object
then to take the mouseX position you can write
var mouseX = mouse.x;
or you can directly take it from
mouse.x;
//still the same

Joshua Usi
- 104
- 1
- 9
0
- Track the mouse position in the X axis is done with an
eventListener
(themousemove
event) - This listener uses a callback function which should change the
transform
(rotate) css property of your element.
// DOM accessor to your HTML element
const rotatingE = document.getElementById('my-rotating-el')
// Event Listener
document.addEventListener('mousemove', e => {
// Callback function
const mX = e.clientX / window.innerWidth * 360
rotatingE.style.transform = 'rotate('+ mX +'deg)'
})
I've made a quick example here

BJRINT
- 639
- 3
- 8