Frizi
Frizi

Reputation: 2940

canvas draw causing NaNs

I'm trying to draw a line using ctx.lineTo in loop.

I have small function in my prototype

this.draw = function(ctx)
{
    ctx.beginPath();
    trace(trail.join(' '));
    for(var i=0;i<trail.length;i++)
    {
        // ctx.lineTo(trail[i].x,trail[i].y);
    }
    ctx.stroke();
}

When I run this, I receive some points traced ([389.272, 722.798] [392.583, 25.069]...) but I see nothing (very surprising)

When I remove the comment from ctx.lineTo, it fails and my trace returns [NaN, NaN] [NaN, NaN].... Constants in drawing function works perfectly (and my points doesn't change), but I need value from variables...

What's wrong? Problem occurs only on Firefox

edit:
trace is simple text assignment to html object
trail is an array of points which are simple objects

function point(x,y)
{
    this.x = x;this.y = y;
    this.toString = function()
    {
        var xs=this.x.toFixed(3);
        var ys=this.y.toFixed(3);
        var xs="     ".substring(0,8-xs.length)+xs;
        var ys="     ".substring(0,8-ys.length)+ys;
        return "["+xs+","+ys+"]";
    }
}

Upvotes: 0

Views: 323

Answers (1)

Pointy
Pointy

Reputation: 413757

There's still not enough information to really answer this, so I'm going to just hazard a guess: change the "point" constructor as follows:

function point(x,y)
{
    this.x = x - 0; this.y = y - 0;
    this.toString = function()
    {
        var xs=this.x.toFixed(3);
        var ys=this.y.toFixed(3);
        var xs="     ".substring(0,8-xs.length)+xs;
        var ys="     ".substring(0,8-ys.length)+ys;
        return "["+xs+","+ys+"]";
    }
}

The idea is to make sure that "x" and "y" are actually numbers and not strings. You could also do this:

    this.x = x - 0; this.y = y - 0;
    if (isNaN(this.x) || isNaN(this.y)) {
      alert("NaN! NaN!  x is " + x + "  y is " + y);

Upvotes: 1

Related Questions