Search code examples
javascriptjquerymousemove

JS - Simple Drawing


I have a problem I have been trying to solve past hour with no success. Here is whole code: http://jsfiddle.net/apbEX/4/

The problem: point.x (and point.y) is NaN for no apparent reason when I use updatePoint function, therefor it doesn't draw the points. But If you comment function updatePoints out, it will normally draw the points (point.x and y has correct values). This means there must be something wrong with the update function, but I can't see any mistake and I used this function without problems in past..

Any help would be greatly appreciated!

the update function:

function updatePoint(point) {
    console.log(pointList[10].x)
        point.eX = pageX - offLeft;
        point.eY = pageY - offTop;         
        var dx = (point.eX - point.origPosX);
        var dy = (point.eY - point.origPosY);
        var mag = Math.sqrt(dx * dx + dy * dy);
        point.velocityX = (dx / mag) * point.speed;
        point.velocityY = (dy / mag) * point.speed;
        point.x += point.velocityX;
        point.y += point.velocityY;       
    } 

Solution

  • When your page loads and you initially call "draw", the variables "pageX" and "pageY" haven't yet been initialized from the "mousemove" event handler; none of those events will have happened at that point.

    Here is an updated (working?) version of your fiddle. The important change I made was:

    var pageX = 0;
    var pageY = 0;
    

    I also made minor changes to make the code work properly in the fiddle context.