【问题标题】:Why do i need press twice to display the element 0?为什么我需要按两次才能显示元素 0?
【发布时间】:2020-11-23 19:08:06
【问题描述】:

我想按一次显示所有元素,

为什么要按两次显示0元素?

我尝试排序 if 语句,但我没有弄明白。

这里是链接fiddle

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

【问题讨论】:

  • 由于您使用 ==,将所有 ifs 测试的 "if" 更改为 "else if" == 1 到 == 4,或者插入 "return;"在每次 fill() 调用之后。
  • 我建议将单词数组更改为对象数组。每个对象都将包含单词和填充选项。这样,将单词添加到列表中并保持一切井井有条会容易得多。
  • @Akxe 能否给我一个示例,说明如何在我的代码中执行此操作?
  • @SPlatten 我会使用 switch-case。
  • @TimTimWong,为什么 switch-caseelse-if 语句 更好?

标签: javascript arrays function for-loop if-statement


【解决方案1】:

因为在第一个 text() 之前没有调用 fill()。顺便说一句,绘图代码应该驻留在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;
}

【讨论】:

  • 所以你是说,我们应该首先调用 textColor,在我们的例子中是 fill(),然后我们将颜色实现到 text,我想这是有道理的,对吧?
  • @HamzaSAMI 默认填充是透明黑色,因此您在绘制时没有颜色。
  • 但是想象一下如果使用fill()来着色,我的假设是对的吗?
  • @HamzaSAMI 不是先绘制文字再填充,而是设置当前的填充颜色,然后用当前的填充颜色绘制文字。
【解决方案2】:

解决问题的功劳归@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;
}

【讨论】:

    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 2023-04-09
    • 2019-05-30
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    相关资源
    最近更新 更多