I know how to do it with black and white
let a = 0;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(map(sin(a), -1, 1, 0, 255));
rect(20, 20, 50);
a += 0.01;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
I would like it to be purple instead of black but I can't do it. I would like to achieve something like this.
I dont know much about p5.js. But simple googling and would offer this solution
let a = 0;
let white;
let purple;
function setup() {
createCanvas(400, 400);
white = color(255, 255, 255);
purple = color(160, 32, 240);
}
function draw() {
background(220);
const temp = map(sin(a), -1, 1, 0, 1);
fill(lerpColor(white, purple, temp));
rect(20, 20, 50);
a += 0.01;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
With lerp color you could create implementation that supports even more colors.
let white = color(255, 255, 255); // at 0 (-1 on sin)
let purple = color(160, 32, 240); // at 0.5 ( 0 on sin)
let blue = color(0,0,255); // at 1 (1 on sin)
let temp = map(sin(a),-1,1,0,1);
if(temp < 0.5){
let temp2 = map(temp, 0, 0.5, 0, 1);
result = lerpColor(white, purple, temp2);
} else {
let temp2 = map(temp, 0.5, 1, 0, 1);
result = lerpColor(purple, blue, temp2);
}
With some refactoring and more work this could support arbitrary number of colors. You could have a sin go through the entire rainbow.
One approach is colorMode(HSB). Hue Saturation Brightness makes it easy to pick a purple hue (280 out of 360), then shift saturation and brightness to fade between grayscale and hue. Saturation and brightness range from 0 to 100.
In this case, I'm fading between 0 and 40 on saturation, and 60 and 100 on brightness. At one extreme, HSB of (280, 0, 100) is pure white. At the other extreme, (280, 40, 60) is purple.
let a = 0;
function setup() {
createCanvas(400, 400);
colorMode(HSB);
}
function draw() {
background(220);
const v = map(sin(a), -1, 1, 0, 40);
fill(280, v, 100 - v);
rect(20, 20, 50);
a += 0.01;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
lerpColor, mentioned in this answer, is probably best for this case, but I'll leave my answer up since it offers some tweakability that lerpColor might not.