To allocate a distinctive color to each section generated using the map function in p5.js, you can follow these steps:
let colors = ['#FF5733', '#9B59B6', '#3498DB', '#2ECC71', '#F1C40F'];
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);
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);
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.
Asked: 2023-07-07 06:44:42 +0000
Seen: 11 times
Last updated: Jul 07 '23