Search code examples
javascriptcolorstrigonometryp5.js

How to go through two colours with sine wave in p5.js


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>

example

I would like it to be purple instead of black but I can't do it. I would like to achieve something like this.


Solution

  • 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.5.0/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.