Ask Your Question
1

In p5.js using the map function, what is the process to allocate a distinctive color to each section that has been generated?

asked 2023-07-07 06:44:42 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-07 07:11:02 +0000

devzero gravatar image

To allocate a distinctive color to each section generated using the map function in p5.js, you can follow these steps:

  1. Define an array of colors, with each element representing a unique color for a section. For example, you can define an array like this:
let colors = ['#FF5733', '#9B59B6', '#3498DB', '#2ECC71', '#F1C40F'];
  1. Inside the draw() function, use the map() function to map the value of a variable that corresponds to the current section to an index of the colors array. For example, if you have divided the canvas into 5 sections using the map() function like this:
let section = map(mouseX, 0, width, 0, 5);
  1. Use the floor() function to convert the section variable to an integer index that corresponds to the colors array. You can use this index to access the corresponding color from the colors array. For example:
let colorIndex = floor(section);
let fillcol = colors[colorIndex];
fill(fillcol);
  1. Use the fill() function to set the fill color for the current section to the selected color.

Putting all steps together, you can create code like this:

let colors = ['#FF5733', '#9B59B6', '#3498DB', '#2ECC71', '#F1C40F'];

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

function draw() {
  background(255);

  let section = map(mouseX, 0, width, 0, 5);
  let colorIndex = floor(section);
  let fillcol = colors[colorIndex];
  fill(fillcol);

  rect(0, 0, width / 5, height);
  rect(width / 5, 0, width / 5, height);
  rect(width * 2 / 5, 0, width / 5, height);
  rect(width * 3 / 5, 0, width / 5, height);
  rect(width * 4 / 5, 0, width / 5, height);
}

This code will map the mouse position along the x-axis to 5 sections of equal width and fill each section with a unique color from the colors array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-07 06:44:42 +0000

Seen: 11 times

Last updated: Jul 07 '23