p5js-在draw()中不能创建多个对象

时间:2018-10-07 20:16:03

标签: javascript p5.js

我正在尝试创建一系列椭圆组成的对象以形成一条线。我可以创建1行,但是,当我尝试介绍第二个时,它没有显示。

如果我随后继续从string1方法中删除draw()的实例,则第二个字符串(string2)现在将显示在正确的区域。

由于某种原因,我不能将两者都在一起。我尝试过添加其他对象实例,这些实例使用p5示例中的省略号,而且效果很好,所以我真的不确定在这里缺少什么。

下面是我的JavaScript,我已经在setup()方法中创建了对象'Harp',并在draw()方法中对其进行了显示/动画处理。

let strings = [];
let visualIncrement = 80;
let initYcoord = -10;

function setup() {
  createCanvas(windowWidth, windowHeight);

  string1 = new Harp(visualIncrement, initYcoord);
  string2 = new Harp(visualIncrement + 360, initYcoord);
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

function draw() {
  background(51);
  string1.move();
  string1.display();
  string2.move();
  string2.display();
}

function Harp(xpos, ypos) {
  this.xpos = xpos; // x position on screen
  this.ypos = ypos; // y position on screen

  this.yspacing = 0.5; // spacing between lines
  this.theta = 0.0; // start angle
  this.period = 100; // pixels before the wave repeats
  this.yvalues; // array for height values
  this.inputAmp = 5.5; // modulated value required for amplitude

  this.w = height;
  this.dx = (TWO_PI * this.period) * this.yspacing;
  this.yvalues = new Array(floor(this.w/this.yspacing));

  this.move = function() {
    this.theta = this.theta += map(400, 0, windowWidth, 0.0, 1.6);
    this.amplitude = map(this.inputAmp, 0, 400, 0.0, 500);
    this.dx = map(80, 0, 400, 0.0, 1.0);

    this.x = this.theta;
    for (var i = 0; i < this.yvalues.length; i++) {
      this.yvalues[i] = sin(this.x)*this.amplitude;
      this.x+=this.dx;
    }
  }
  this.display = function() {
    fill(255);
    translate(this.xpos, this.ypos);
    for(let x = 0; x < this.yvalues.length; x++) {
      strokeWeight(20);
      stroke(255);
      translate(0, 9);
      ellipse(height/80+this.yvalues[x], x*this.yspacing, 0.2, 0.02);
      // ellipse(this.xpos, this.ypos, 0.2, 0.02);
    }
  }
}

这里也有一个CodePen:https://codepen.io/joeqj2/pen/gBLPvg

我从来没有遇到过这个问题,完全被它困扰,无法在网上找到任何东西。

1 个答案:

答案 0 :(得分:0)

您可以在translate()函数中调用display()。请记住,翻译堆栈。例如:

translate(100, 0);
translate(0, 100);
ellipse(0, 0, 20, 20);

此代码将在100, 100处绘制一个椭圆,因为对translate()的调用会堆栈。

返回到代码,绘制第一条线时,调用translate()移至绘制该线的位置。然后绘制第二行,再次调用translate()。但是请注意,第二次translate()的调用是在第一次调用的顶部完成的,因此第二行结束于屏幕边缘之外的某处。这也是为什么如果删除第一行会显示第二行的原因。

有两种解决方法:

  • 您可以消除对translate()的调用,并直接在图形中使用坐标。
  • 或者您可以调用push()pop()函数来隔离每一行的翻译。

更多信息可以在the reference中找到。

相关问题