JavsScript — Track mouse position relative to the middle of the screen

749 Views Asked by At

I am struggling with the maths here. My goal is to generate a value based on the mouse position relative to the middle of the window. The output should be a range of -1 to 1, meaning that the extreme left is -1, middle of the window 0 and extreme right 1. How can I achieve that?

Thank you in advance.

Pseudo-code

  • Track mouse position relative to the middle of the screen
  • Convert this value to a range of -1 to 1 based on the window size
  • Use value somewhere else

Code

// Mouse event
var mousePosX, mousePosY, mouseOffsetX, mouseOffsetY;

onmousemove = function (e) {
  // console.log(`mouse location = X: ${e.x}, Y: ${e.y}`);
  mouseOffsetX = e.offsetX / percentX(100);
  // mouseOffsetY = e.y / percentY(100)
  mousePosX = e.pageX / percentX(100) - percentX(100);
  mousePosY = e.y / percentY(100);

  // if (mousePosX => 0.5) {
  //   mousePosX = mousePosX*1
  // }else {
  //   mousePosX = mouse*-1
  // }

};
1

There are 1 best solutions below

0
On BEST ANSWER

Here is one way to do it. Divide mouse x-position with windowWidth so the position is between 0-1. Start from -1 and add xValue/windowWidth*2 so it is mapped between -1 and 1. With y position start from 1 so top 1 and bottom is -1.

onmousemove = function (e) {
    
    let windowHeight = window.innerHeight
    let windowWidth = window.innerWidth
    let xValue = e.x
    let yValue = e.y

    let mousePosX = -1+(xValue/windowWidth)*2
    let mousePosY = 1-(yValue/windowHeight)*2
};