Home > Mobile >  How to loop through color set and apply to "fill" in p5.js?
How to loop through color set and apply to "fill" in p5.js?

Time:04-25

For this sketch, I wanted to have the stars have slightly different colors, to emulate how actual stars are not just pure white light. I tried a few different methods of doing this without any success. How would you accomplish this?

Looking to modify the first fill(255) to draw each star in a distinct color from a set. I tried using an array of around 4 colors and accessing the indexes. I tried using random() to choose rgb values a few numbers away from 255. I'm fairly new at this, so forgive my lack of proper terminology. I think I likely just didn't put my loop through the arrays in the correct spot.

Full code is here. Thanks in advance!

function starsMoon() { //create star cluster and moon
  randomSeed(300);
  translate(-width * 2, -height * 2);
  noStroke();
  fill(255);
  for (let i = 0; i < 300; i  ) { // stars
      // this is where I initially put the fill(colorSet[i])
      ellipse(random(0,width * 4)   i, random(0,height * 4)   i, 2, 2);
  }
  fill(255);
  ellipse(width * 1.25, height * 2, 100, 100); // moon
}

CodePudding user response:

Yeah either of those would work!

Random offset:

function starsMoon() { //create star cluster and moon
  randomSeed(300);
  translate(-width * 2, -height * 2);
  noStroke();
  for (let i = 0; i < 300; i  ) { // stars
      fill(250   ((random() - 0.5) * 2 * 5)) // random fill between 245 - 255
      ellipse(random(0,width * 4)   i, random(0,height * 4)   i, 2, 2);
  }
  fill(255);
  ellipse(width * 1.25, height * 2, 100, 100); // moon
}

To rotate through colors from a list you just need take the index mod the number of colors:

function starsMoon() { //create star cluster and moon
  randomSeed(300);
  translate(-width * 2, -height * 2);
  noStroke();
  let colors = [
      color(210, 180, 170), 
      color(40, 100, 29), 
      color(100, 100, 110), 
      color(102, 210, 12)
  ]
  for (let i = 0; i < 300; i  ) { // stars
      fill(colors[i % colors.length])  // loop through colors
      ellipse(random(0,width * 4)   i, random(0,height * 4)   i, 2, 2);
  }
  fill(255);
  ellipse(width * 1.25, height * 2, 100, 100); // moon
}

Cool project btw!

  • Related