Uncaught type error

Any idea why I would get an “Uncaught type error: Cannot read property ‘x’ of undefined” in this code? The error is at line 89.


    
    var w,h;
var c,ctx;
var pixels,imgdata;            

        
window.addEventListener('load', function()
{                     
    init();
    setInterval(draw,15);
});
        
function color(r,g,b,a)
{
    this.r=r;
    this.g=g;
    this.b=b;
    this.a=a;
}

function vert2d(x,y)
{
     this.x=x;
     this.y=y;
}

function boundbox(maxx,maxy,minx,miny)
{
     this.maxx=maxx;
     this.maxy=maxy;
     this.minx=minx;
     this.miny=miny;
}

function triangle(p1,p2,p3)
{
     this.p1=p1;
     this.p2=p2;
     this.p3=p3;
}

function init()
{
    c=document.querySelector("canvas");
    ctx=c.getContext('2d');
    c.width=window.innerWidth;
    c.height=window.innerHeight;
    w=c.width;
    h=c.height;
}
        
function setPixel(x,y,r,g,b,a)
{    
    var index=(x+y*imgdata.width)*4;
    pixels[index]=r;
    pixels[index+1]=g;
    pixels[index+2]=b;
    pixels[index+3]=a;  
}

function crossProduct(u,v)
{
    return (u.x*v.y - u.y*v.x);
}

function findBoundingBox(t)
{
    var maxx=Math.max(t.p1.x,Math.max(t.p2.x,t.p3.x));
    var maxy=Math.max(t.p1.y,Math.max(t.p2.y,t.p3.y));
    var minx=Math.min(t.p1.x,Math.min(t.p2.x,t.p3.x));
    var miny=Math.min(t.p1.y,Math.min(t.p2.y,t.p3.y));
    
    return new boundbox(maxx,maxy,minx,miny);
}

function drawTri(t, c)
{
     // find bounding box of triangle
     var b=findBoundingBox(t);
     var vs1=new vert2d(t.p2.x-t.p1.x, t.p2.y-t.p1.y);
     var vs2=new vert2d(t.p3.x-t.p1.x, t.p3.y-t.p1.y);
     
     // iterate through box area
     for(i=b.minx;i<b.maxx;i++)
     {
         for(j=b.miny;j<b.maxy;j++)
         {
              var k=new vert2d(i-t.p1.x, j-t.p1.y);  // ERROR HERE
              var s=crossProduct(k, vs1) / crossProduct(vs1,vs2);
              var t=crossProduct(vs1,k) / crossProduct(vs1,vs2);
              
              if((t>=0)&&(s>=0)&&((s+t)<=1))
                  setPixel(i,j,c.r,c.g,c.b);
         }
     }  
}

function draw()
{    
    imgdata=ctx.getImageData(0,0,w,h);
    pixels=imgdata.data;
    
    var tri=new triangle(new vert2d(100,100),new vert2d(300,300), new vert2d(50,200));
    
    drawTri(tri, new color(0,0,255,0.3));
    
    ctx.putImageData(imgdata,0,0);

}
        
              var k=new vert2d(i-t.p1.x, j-t.p1.y);  // ERROR HERE
              var s=crossProduct(k, vs1) / crossProduct(vs1,vs2);
              var t=crossProduct(vs1,k) / crossProduct(vs1,vs2);

The t variable is undefined until execution gets to the var t line, where it it then given a value.

When t is undefined, it doesn’t have a p1 object, which is why there is no x property from the non-existing p1 from the undefine t variable.

Yes I’ve just realized that…silly error! Thank you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.