P5.Js - 如何在特定 x 值的 while 循环中更改 line() 颜色?

P5.Js - how can I change line() color in a while-loop on specific x-values?

我正在做一个需要以下内容的小作业:

我必须创建一个在屏幕上绘制 30 行的 while 循环。第 7 行和第 23 行应为红色。

因为我还在想办法解决问题,所以我尝试给距离 stroke(0) 最近的 2 条线涂上颜色; to stroke(255);, 但无论我尝试什么,我都无法让 2 行改变颜色

在这个例子中,我尝试嵌套一个 while 循环,但目前还没有成功。我还尝试删除嵌套的 while 循环并添加一个具有相同变量的 "if" 语句 (x == 40 && x == 60) 但仍然没有任何反应。我该怎么做才能解决这个问题?

var x = 20;
var stap = 20;
var stop = 600;

function setup () {
  createCanvas(700, 700);
}

function draw () {
  stroke(0);

  while(x < stop) {
    line(x, 60, x, 80);
    x += stap;

    while (x == 40 && x == 60) {
      stroke(255);
    } 
  }
}

您正在画线后 if 语句中设置描边颜色。请务必先设置颜色,然后再绘制您要绘制的任何内容。

while loop 的语法如下:

while (condition) {
  statements to execute while the condition is true
}

你的情况:

while (line_number <= 30) {
  y = step_size * line_number;
  // Determine which color to use
  if (line_number == 7 || line_number == 23) {
    // Set color to RED
    line_color = color(127, 0, 0);
  } else {
    // Set alternate color
    line_color = color(127, 127, 127);
  }
  // Set the color to draw the line
  stroke(line_color);
  // Draw a horizontal line
  line(0, y, width, y);
  // Go to the next line
  line_number++;
}

你已经很接近了,你只是不需要那个内部 while 循环!

为了完整起见,这里有一个 p5 解决方案:

var x = 20;
var stap = 20;
var stop = 600;

function setup() {
  createCanvas(700, 700);
}

function draw() {

  while (x < stop) {
    if (x === 20 || x === 40) {
      stroke(255, 0, 0);
    } else {
      stroke(0);
    }

    line(x, 60, x, 80);
    x += stap;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js"></script>

您说过要显示最近的两条线,这些线位于 x 位置 20 和 40,而不是 40 和 60!