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

时间:2019-01-11 15:16:38

标签: javascript p5.js

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

我必须创建一个while循环,在屏幕上绘制30条线。 7号线和23号线应涂成红色。

由于我仍在尝试解决问题,因此尝试为stroke(0)中最近的2条线上色;到stroke(255);,但是无论我如何尝试,我都无法让两行更改颜色

在此示例中,我尝试嵌套while循环,到目前为止,该循环不起作用。我还尝试删除嵌套的while循环,并添加具有相同变量(x == 40 && x == 60)的“ if”语句,但仍然没有任何反应。我该怎么做才能解决此问题?

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);
    } 
  }
}

3 个答案:

答案 0 :(得分:2)

您非常亲密,只需要内部的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!

答案 1 :(得分:0)

您将在绘制线条后的if语句 中设置笔触颜色。确保先设置颜色,然后绘制要绘制的任何内容。

答案 2 :(得分:0)

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++;
}