<div class="wrap">
  <div class="box"></div>
</div>
.wrap {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 200px;
  height: 200px;
  background: red;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}
const box = document.querySelector('.box')

window.addEventListener('mousemove', e => {
  let corBox = box.getBoundingClientRect()
  let y, x
  if(e.clientY > corBox.y) {
    if (e.clientY > corBox.y && corBox.y + corBox.height > e.clientY) {
      y = 0
    } else {
      y = e.clientY - corBox.y - corBox.height
    }
  } else {
    if (e.clientY > corBox.y && corBox.y + corBox.height > e.clientY) {
      y = 0
    } else {
      y = corBox.y - e.clientY 
    }
  }
  if(e.clientX > corBox.x) {
    if (e.clientX > corBox.x && corBox.x + corBox.width > e.clientX) {
      x = 0
    } else {
      x = e.clientX - corBox.x - corBox.width
    }
  } else {
    if (e.clientX > corBox.x && corBox.x + corBox.width > e.clientX) {
      x = 0
    } else {
      x = corBox.x - e.clientX 
    }
  }
  box.textContent = `x: ${x} y: ${y}`
})

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.