Hans Chnuspi Hans Chnuspi -4 years ago 81
HTML Question

Why do my variables keep showing up as NaN?

So tried to make a small script to track mouse movements. I wanted to calculate the average speed and average duration in which the mouse does not move.

However, my variables show up as NaN in console when I print them out.



var avgSize = 0;
var avgSpeed = 0;
var measures = 0;
var lastX;
var lastY;
var lastMillis;

var eventDoc, doc, body, pageX, pageY;
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");

// Mouse moved
document.onmousemove = function(event) {
event = event || window.event; // IE-ism

// If pageX/Y aren't available but clientX/Y are, calculate pageX/Y - logic taken from jQuery
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) || document;
doc = eventDoc.documentElement;
body = eventDoc.body;

event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}

// Calculate dot size
dotSize = (Date.now() - lastMillis) / 50;
if (dotSize > window.innerHeight / 10) {
dotSize = window.innerHeight / 10;
}

// Draw dots
if (dotSize > 2) {
ctx.beginPath();
ctx.arc(lastX, lastY, dotSize, 0, 2 * Math.PI);
ctx.stroke();
ctx.fill();
}

measure(Math.abs(event.pageX - lastX) + Math.abs(event.pageY - lastY), dotSize);

// Variables for comparison
lastX = event.pageX;
lastY = event.pageY;
lastMillis = Date.now();
}

// Calculate averages
function measure(speed, size) {
measures++;
avgSpeed = avgSpeed - (avgSpeed / measures) + speed / measures;
avgSize = avgSize - (avgSize / measures) + size / measures;

console.log("average speed: " + avgSpeed + " average size: " + avgSize);
}

<canvas id="canvas"></canvas>





EDIT: Added missing declarations i accidentally deleted.

Answer Source

The following variables are not defined in your mousemove handler when used for the first time. You should define these before/during the first move.

lastX = event.pageX;
lastY = event.pageY;
lastMillis = Date.now();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download