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();
};

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

编辑


项目链接:转换库

4

1 回答 1

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);
};

这会将fands变量设置为从函数返回的值rotate()。但是等等,类中的rotate()函数Point没有返回任何东西!所以现在this.f未定义this.s

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

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

退后一步,我想知道你为什么要自己做这一切。Processing 有自己的rotate()功能,可以为您完成所有这些工作。你为什么不直接使用它们呢?

于 2017-02-14T02:52:10.500 回答