数组 return 不一致 (p5js)

array return inconsistancy (p5js)

在绘图程序中,线坐标存储在一个数组中,以便重新绘制绘图。有时,返回的图像不完全完整,并且在按下鼠标之前会丢失部分线条(这在 p5js 中)。我不确定如何解决这个问题(抱歉,我是新手)。

let lineCor = [];
let state = "help";
let r, g, b;
let symmetry = 8;
let angle = 360 / symmetry;

function setup() {
  createCanvas(windowWidth, windowHeight);
  background(220);
  r = 50;
  g = 0;
  b = 0;
}

function draw() {
  helpScreen();
  copyDrawing();
}

function copyDrawing() {
  if (state === "draw") {
    
    push();
    angleMode(DEGREES);
    translate(windowWidth / 2, windowHeight / 2);
    displayImg();
    pop();
    
    if (mouseIsPressed) {
      let linePos = {
        x: mouseX - windowWidth / 2,
        y: mouseY - windowHeight / 2,
        px: pmouseX - windowWidth / 2,
        py: pmouseY - windowHeight / 2,
      };
      lineCor.push(linePos);
    }
  }
}

function displayImg() {
  stroke(r, g, b);
  for (let i = 0; i < symmetry; i++) {

    for (let n = 0; n < lineCor.length; n++) {
      rotate(angle);
      line(lineCor[n].x, lineCor[n].y, lineCor[n].px, lineCor[n].py);
      push();
      scale(1, -1);
      line(lineCor[n].x, lineCor[n].y, lineCor[n].px, lineCor[n].py);
      pop();
    }
  }
}

function mouseWheel() {
  if (event.deltaY > 0) {
    if (r < 255) {
      r += 10;
    } 
    else if (g < 255) {
      g += 10;
    } 
    else if (b < 255) {
      b += 10;
    }

  } else {
    if (r > 0) {
      r -= 10;
    } 
    else if (g > 0) {
      g -= 10;
    } 
    else if (b > 0) {
      b -= 10;
    }
  }
}

function helpScreen() {
  if (state === "help") {
    background(160);
    textAlign(CENTER, CENTER);
    textSize(windowWidth * 0.04);
    text("Welcome to this kaleidiscope drawing program", windowWidth / 2, windowHeight / 3);
    textSize(windowWidth * 0.015);
    text("To change color, scroll the mousewheel. Press 's' to start drawing. Press 'c' to clear the screen. Press 'h' to return to return to this help screen.", windowWidth / 2, 1.5 * windowHeight / 3);
  }
}

//commands for the keybinds
function keyTyped() {
  if (key === "c") {
    setup();
    lineCor = [];
  }

  if (key === "h") {
    setup();
    state = "help";
  }

  if (key === "s") {
    setup();
    state = "draw";  
  }

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>

问题出在这里:

for (let i = 0; i < symmetry; i++) {
  for (let n = 0; n < lineCor.length; n++) {
    rotate(angle);
    line(lineCor[n].x, lineCor[n].y, lineCor[n].px, lineCor[n].py);
    push();
    scale(1, -1);
    line(lineCor[n].x, lineCor[n].y, lineCor[n].px, lineCor[n].py);
    pop();
  }
}

在调试的时候发现问题是因为background(),这就意味着没有画出所有的线。经过进一步的实验,我发现只有当 lineCor 的元素个数为偶数时才会出现这种情况。为什么会这样?

因为rotate()。你看,旋转应该只发生 8 次 (let symmetry = 8),但在你的代码中,它发生在每一行。 当 lineCor.length 是偶数时,这会导致它在同一位置多次绘制线条(使其看起来有些线条根本没有绘制)。

通过将 rotate() 移动到外部 for-loop 即可轻松解决此问题。

for (let i = 0; i < symmetry; i++) {
  rotate(angle);      
  for (let n = 0; n < lineCor.length; n++) {