How to cycle between two colors using lerp

I’m trying to smoothly lerp back and forth between two colors repeatedly. The following changes from red to blue and then suddenly shifts back to red when the sketch loops. Is there a way to shift from red to blue to red to blue smoothly? Maybe a way to use a sine wave to control the change?

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

function draw() {
  background(220);
  fill(lerpColor(color('#FF2D00'),color('#0059FF'),(millis()%5000)/5000));
  square(50, 50, 150);
}

In the p5js editor: p5.js Web Editor


let i=0.0; 
let a=1.0; 

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

function draw() {
  background(220);
  
  fill(lerpColor(color('#FF2D00'),color('#0059FF'),  float(i/500.0) ) ); 
  
  square(50, 50, 150);
  i=i+a;
  if(i>500)
     a=-1.0; 
  if(i<0)
     a=1.0; 
}


Thank you so much for your help!

1 Like