Почему мне нужно дважды нажать, чтобы отобразить элемент 0? - PullRequest
1 голос
/ 03 августа 2020

Я хочу нажать один раз, чтобы отобразить все элементы,

почему я должен нажать два раза, чтобы отобразить 0 элементов?

Я пытаюсь заказать операторы if, но не сделал этого т разобраться.

вот ссылка скрипка

var words = ['rainbow', 'heart', 'purple', 'friendship', 'love'];
  function setup() {
    createCanvas(400, 400);
  }
  function draw() {
    background(0);
  
    textSize(32);
    text(words[i]);
  
  }
  function mousePressed() {
    for (let i = 0; i < words.length; i++) {

      text(words[i], 100, i * 50 + 50);
      if (i == 0) {
        fill(255, 0, 0);
      }

      if (i == 1 ) {
        fill(0, 50, 100, 300);
      }
      if (i == 2) {
        fill(0, 165, 300, 200);
      }
      if (i == 3) {
        fill(0, 50, 100, 300);
      }

      if (i == 4) {
        fill(0, 50, 100, 300);
      }
    }
  }

Ответы [ 2 ]

1 голос
/ 03 августа 2020

Потому что fill() не был вызван до первого text(). Кстати, код чертежа должен находиться в draw().

const words = ['rainbow', 'heart', 'purple', 'friendship', 'love'],
    colors = [
        [255, 0, 0],
        [0, 50, 100, 300],
        [0, 165, 300, 200],
        [0, 50, 100, 300],
        [0, 50, 100, 300],
    ];
let isMousePressed = false;
function setup() {
    createCanvas(400, 400);
}
function draw() {
    background(0);
    textSize(32);
    if (isMousePressed)
        words.forEach((w, i) => {
            fill.call(null, colors[i]);
            text(w, 100, (i + 1) * 50);
        });
}
function mousePressed() {
    isMousePressed = true;
}
0 голосов
/ 04 августа 2020

Кредиты за решение принадлежат @TimTimWong, я просто объясняю свой комментарий.

const words = [
  {
    word: 'rainbow',
    colors: [255, 0, 0],
  },
  {
    word: 'heart',
    colors: [0, 50, 100, 300],
  },
  {
    word: 'purple',
    colors: [0, 165, 300, 200],
  },
  {
    word: 'friendship',
    colors: [0, 50, 100, 300],
  },
  {
    word: 'love',
    colors: [0, 50, 100, 300],
  }
];
let isMousePressed = false;
function setup() {
  createCanvas(400, 400);
}
function draw() {
  background(0);
  textSize(32);
  if (isMousePressed) {
    words.forEach(({ word, color }, i) => {
      fill.call(null, color);
      text(word, 100, (i + 1) * 50);
    });
  }
}
function mousePressed() {
  isMousePressed = true;
}
...