Home > database >  How to calculate a mouse position like 0 will return -8 and 1000 will return 8 number?
How to calculate a mouse position like 0 will return -8 and 1000 will return 8 number?

Time:05-12

As I'm trying to get into animation using a mousemove event I encountered a problem on how to get the specific number with a limit in both left and right direction while moving the mouse event

like if the mouse position is in 500 inside a container of 1000 width a function should return 0

Also on How to reverse the return like if it's on 0 it should return 8

HTML:

<div >
  <h1>Mouse Move</h1>
  <p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus, 
    magni.
  </p>
</div>

CSS:

body {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
  font-weight: 400;
  line-height: 1.5;
  background-color: #2c3e50;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.container {
  background-color: white;
  color: #2c3e50;
  max-width: 300px;
  padding: 15px;
  border-radius: 3px;
}

JS:

const CARD_CONTAINER = document.querySelector('.container');
let window_width = window.innerWidth;

window.addEventListener('mousemove', (event) => {
  let getTranslateX = (event.clientX / window_width) * 8;

  console.log(getTranslateX);

  CARD_CONTAINER.style.transform = `translateX(-${getTranslateX}px)`;
});

CodePudding user response:

const ANIMATION_WIDTH=1000;
const RANGE=8;
const result=(mousePosition-(ANIMATION_WIDTH/2))*RANGE/(ANIMATION_WIDTH/2);
  • Related