需要协助以启用P5画线功能

时间:2020-02-01 17:44:21

标签: javascript processing p5.js

我正在尝试复制我在这里工作的粗线连接功能https://editor.p5js.org/knectar/sketches/0Thp1IJn,但使用数组中的对象。看起来这段代码应该可以工作,但是并没有根据需要填充值来绘制连接线。任何帮助将不胜感激!

以下是代码(或此处为https://editor.p5js.org/knectar/sketches/HYPwtjge):

var dotCount = 2;
var dot;
var xTempPos, yTempPos;
var xEndPos, xEndPos; 

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

  noStroke();
  fill(200);
  for (let i = 0; i < dotCount; i++) {
    dotArray.push(new Dot());
  }
}

function draw() {
  // background(0);

  for (let i = 0; i < dotArray.length; i++) {
    dotArray[i].sketch();    
  }

  for (let i = dotArray.length - 1; i > 0; i--) {
    dotArray[i].connect();

    xEndPos = dotArray[i].xPos;
    xEndPos = dotArray[i].yPos;

    xTempPos = dotArray[i - 1].xPos;
    yTempPos = dotArray[i - 1].yPos;

    console.log(xTempPos);

  }
}

class Dot {

  constructor() {
    this.xStartPos = random(width);
    this.yStartPos = random(height);
    this.rad = 5;
  }

  sketch() {
    ellipse(this.xStartPos, this.yStartPos, this.rad);
  }

  connect() {
    stroke(200);
    strokeWeight(1);

    line(this.xStartPos, this.yStartPos, xTempPos, yTempPos);

    if (xTempPos <= xEndPos) {
      xTempPos = xTempPos + 1;
    }

    if (yTempPos <= xEndPos) {
      yTempPos = yTempPos + 1;
    }

  }

}```

1 个答案:

答案 0 :(得分:1)

缺少dotArray的声明。

var dotArray = [];

此外,它必须是xStartPosyStartPos,而不是xPosyPos

查看示例:

var dotCount = 2;
var dot;
var xTempPos, yTempPos;
var xEndPos, xEndPos; 
var dotArray = [];

function setup() {
  //createCanvas(windowWidth, windowHeight);
  createCanvas(400, 200);

  for (let i = 0; i < dotCount; i++) {
    dotArray.push(new Dot());
  }
}

function draw() {
  background(255, 255, 255);

  fill(255, 0, 0);
  stroke(255, 0, 0);
  strokeWeight(1);

  for (let i = 0; i < dotArray.length; i++) {
    dotArray[i].sketch();    
  }

  for (let i = dotArray.length - 1; i > 0; i--) {
    dotArray[i].connect();

    xEndPos = dotArray[i].xStartPos;
    xEndPos = dotArray[i].yStartPos;

    xTempPos = dotArray[i - 1].xStartPos;
    yTempPos = dotArray[i - 1].yStartPos;

    console.log(xTempPos);

  }
}

class Dot {

  constructor() {
    this.xStartPos = random(width);
    this.yStartPos = random(height);
    this.rad = 5;
  }

  sketch() {
    ellipse(this.xStartPos, this.yStartPos, this.rad);
  }

  connect() {

    line(this.xStartPos, this.yStartPos, xTempPos, yTempPos);

    if (xTempPos <= xEndPos) {
      xTempPos = xTempPos + 1;
    }

    if (yTempPos <= xEndPos) {
      yTempPos = yTempPos + 1;
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>