p5.j​​s实例模式:无法读取属性' 0'未定义的

时间:2016-10-23 21:53:10

标签: object push processing instance p5.js

我在全局模式下有一个完美的草图,我现在将它带到实例模式的另一个文档中,因为它与3D / WEBGL草图并列。

每当我点击推送一个新的Pulse()实例时,我得到"无法读取属性' 0'未定义"作为回报来自draw()中的for()循环。正如我所说它在全局模式下完美运行,所以我必须在这里使用语法错误,但我无法找到在p5实例模式下使用对象的任何示例。我不知道为什么它无法从数组中读取,或者为什么它无法推动。

在p5.js实例模式中推送到对象数组时,我不确定语法。我也尝试了s.pulses.push(new s.Pulse())和s.pulses.s.push(new s.Pulse())的变体,但是这些返回推送错误。下面的代码似乎在推动,但数组无法读取。

任何帮助都会很棒,谢谢。

var twoDee = function(s) {
var cnv;
var cnvWidth, cnvHeight;
var pulsesAmount;
var pulses = [];

s.setup = function() {
    s.cnvWidth = s.windowWidth;
    s.cnvHeight = document.getElementById('sketch-wrap-bleed-bottom').offsetHeight;
    s.cnv = s.createCanvas(s.cnvWidth, s.cnvHeight, s.P2D);
    s.cnv.parent("sketch-wrap-bleed-bottom");
    s.pulsesAmount = 0;
}

s.draw = function() {
    s.background(40);
    for (var i = 0; i < s.pulsesAmount; i++) {
        s.pulses[i].move(); // problem here
        s.pulses[i].display();
    }

    s.noFill();
    s.stroke(255);
    s.ellipse(s.mouseX, s.mouseY, 30, 30);
}

s.Pulse = function() {
    this.size = 20;
    this.grow = 0.5;
    this.xPos = s.width/2 + 200;
    this.yPos = s.height/2;
    this.opacity = 255;

    this.move = function() {
        this.size += this.grow;
        this.opacity = map(this.size, 0, 60, 255, 0);
    }

    this.display = function() {
        s.noFill();
        s.strokeWeight(2);
        s.stroke(242, 202, 102, this.opacity);
        s.translate(this.xPos, this.yPos);
        s.ellipse(0, 0, this.size, this.size);
        s.translate(-this.xPos, -this.yPos);
    }
}

s.mousePressed = function() {
    s.pulsesAmount += 1;
    s.pulses = s.push(new s.Pulse());
}

}

1 个答案:

答案 0 :(得分:1)

您只需要使用s变量来处理来自P5.js的内容,例如mouseXsetup()函数。

对于您声明的内容,例如pulsespulsesAmount变量,您不使用s变量。因此,您的for循环应如下所示:

for (var i = 0; i < pulsesAmount; i++) {
    pulses[i].move();
    pulses[i].display();
}

修改:修复该问题后,您还有其他问题。这条线没有意义:

pulses = s.push(new Pulse());

请参阅the P5.js reference以更好地了解push()功能的作用。它与数组无关。

您可能正在考虑append()函数,但即使这样,您的语法也会关闭。您必须将数组与要添加到其中的值一起传递给函数。像这样:

s.append(pulses, new Pulse());

修复之后,你仍然会遇到其他一些问题(比如没有使用s变量来进入map()函数),但这应该会让你朝着正确的方向前进。 / p>

相关问题