Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.