为什么我的变量会一直显示为NaN?

时间:2017-06-12 14:06:54

标签: javascript html

因此尝试制作一个小脚本来跟踪鼠标移动。我想计算鼠标不移动的平均速度和平均持续时间。

但是,当我打印出来时,我的变量在控制台中显示为NaN。

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>

编辑:添加了我意外删除的遗漏声明。

1 个答案:

答案 0 :(得分:2)

首次使用时,mousemove处理程序中未定义以下变量。您应该在第一次移动之前/期间定义这些。

lastX = event.pageX;
lastY = event.pageY;
lastMillis = Date.now();

编辑:原始代码已更新,但缺少代码,因此这是一个新答案

您的变量仍然未定义,因此我建议您在第一步中定义它们:

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

    if (typeof lastX == "undefined") {
        lastX = event.pageX;
    }

    if (typeof lastY == "undefined") {
        lastY = event.pageY;
    }

    if (typeof lastMillis == "undefined") {
        lastMillis = Date.now();
    }

    ...