2017-02-14 124 views
1

我编程,可以在汗学院变换的多边形图书馆的财产,但我不断收到此错误:汗学院:无法读取未定义

Cannot read property 'x' of undefined 

不带行号。

我的代码:

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

Point.prototype.rotate = function(around,degrees) { 
    angleMode = "degrees"; 
    var aX = around.x; 
    var aY = around.y; 
    var cX = this.x; 
    var cY = this.y; 
    var dist = sqrt(sq(cX-aX)+sq(cY-aY)); 
    var currentTheta = asin(dist/cY); 
    var gamma = degrees+currentTheta; 
    this.x = cos(gamma)*dist+aX; 
    this.y = sin(gamma)*dist+aY; 
}; 

var Line = function(x1,y1,x2,y2) { 
    this.f = new Point(x1,y1); 
    this.s = new Point(x2,y2); 
}; 

Line.prototype.draw = function() { 
    line(this.f.x,this.f.y,this.s.x,this.s.y); 
}; 

Line.prototype.rotate = function(around,degrees) { 
    this.f = this.f.rotate(around,degrees); 
    this.s = this.s.rotate(around,degrees); 
}; 

var Polygon = function(x,y){ 
    if(x.length!==y.length){return;} 
    this.sides = x.length; 
    this.x = x; 
    this.y = y; 
    this.lines = new Array(this.sides); 
    this.lines[0] = new Line(this.x[this.sides-1],this.y[this.sides-1],this.x[0],this.y[0]); 
    for(var i=1;i<this.sides;i++){ 
     this.lines[i] = new Line(this.x[i-1],this.y[i-1]); 
    } 
}; 

Polygon.prototype.draw = function() { 
    for(var i=0;i<this.sides;i++){ 
     this.lines[i].draw(); 
    } 
}; 

Polygon.prototype.rotate = function(around,degrees) { 
    for(var i=0;i<this.sides;i++){ 
     this.lines[i].rotate(around,degrees); 
    } 
}; 

var p = new Polygon([10,20,40],[40,20,15]); 

var draw = function() { 
    background(255,255,255); 
    fill(0,0,0); 
    stroke(0,0,0); 
    p.rotate(new Point(20,20),1); 
    p.draw(); 
}; 

然而,我仍然不知道为什么它会抛出错误,特别是因为它给错误所在没有方向。

编辑


链接到项目: Transformation Library

+1

那个代码本身并没有给出这样的错误,还有别的吗? –

+0

@JaromandaX这些功能在khanacademy中是默认的,填充和描边用于绘制。 –

+0

编辑:添加到项目链接@JaromandaX –

回答

3

让我们先从你的Point类及其rotate()功能:

Point.prototype.rotate = function(around,degrees) { 
    angleMode = "degrees"; 
    var aX = around.x; 
    var aY = around.y; 
    var cX = this.x; 
    var cY = this.y; 
    var dist = sqrt(sq(cX-aX)+sq(cY-aY)); 
    var currentTheta = asin(dist/cY); 
    var gamma = degrees+currentTheta; 
    this.x = cos(gamma)*dist+aX; 
    this.y = sin(gamma)*dist+aY; 
}; 

这个函数做一些数学并设置this.xthis.y变量。到目前为止这么好(免责声明:我没有检查过这个数学,但那不是重点)。但是请注意,这个函数不会返回任何东西。

现在让我们去你的Line类及其rotate()功能:

Line.prototype.rotate = function(around,degrees) { 
    this.f = this.f.rotate(around,degrees); 
    this.s = this.s.rotate(around,degrees); 
}; 

这台fs变量从rotate()函数的返回值。但是请等待,Point类中的rotate()函数不会返回任何内容!所以现在this.fthis.s都是undefined

你有类似的问题,你的Polygon类调​​用Line类的rotate()函数。

因此要解决您的问题,您需要使用rotate()函数来返回某些内容,或者只需调用它们而不是期望返回值。

退一步,我想知道你为什么要自己做这一切。处理有它自己的rotate()功能,为你做这一切。你为什么不直接用它们呢?

+0

谢谢!我错过了... 我自己写这个,因为它是一个项目。 –

+1

@EricHe如果这解决了您的问题,您可能希望将其标记为答案 –