Aleksandr
Aleksandr

Reputation: 437

Mouse speed on JavaScript

The code snippet below calculates the speed of the mouse cursor on the screen. It appears to work correctly, however, I have some questions about how it works.

var div = document.body.children[0],
    isOverElem, cX, cY, pX, pY, cTime, pTime;

div.addEventListener('mouseover', function(event) {
  if (isOverElem) return;

  isOverElem = true;

  pX = event.pageX;
  pY = event.pageY;
  pTime = Date.now();

  this.addEventListener('mousemove', move);
});

div.addEventListener('mouseout', function(event) {
  if ( event.relatedTarget && !this.contains(event.relatedTarget) ) {
    isOverElem = false;

    this.removeEventListener('mousemove', move);

    this.innerHTML = '';
  }
});

function move(event) {
  var speed;

  cX = event.pageX;
  cY = event.pageY;
  cTime = Date.now();

  if (pTime == cTime) return; // mouseover with mousemove

  speed = Math.sqrt( Math.pow(pX - cX, 2) + Math.pow(pY - cY, 2) ) / (cTime - pTime);

  this.innerHTML = 'Mouse speed: ' + speed;

  setTimeout(function() {
    pX = cX;
    pY = cY;
    pTime = cTime;
  }, 10);
}
div {
  width: 80%;
  height: 200px;
  padding: 10px;
  line-height: 200px;
  font-size: 1.5em;
  border: 2px solid red;
}
<div></div>

I don't understand the following line:

speed = Math.sqrt( Math.pow(pX - cX, 2) + Math.pow(pY - cY, 2) ) / (cTime - pTime);

Why can't this just use (pX - cX)/(cTime - pTime)? Why does it require a more complicated equation that includes Math.sqrt and Math.pow? I am interested in the algorithm and whether the script is correct.

Upvotes: 0

Views: 669

Answers (1)

guysigner
guysigner

Reputation: 2922

(pX - cX) / (cTime - pTime) would be the horizontal speed.

(pY - cY) / (cTime - pTime) would be the vertical speed.

If you go horizontally and then vertically, you would travel more distance then if you would have gone straight from X to Y. So, to get the minimal distance between X and Y, you have to use the distance formula.

enter image description here

Upvotes: 2

Related Questions