# How to cycle between two colors using lerp

**URL:** <https://discourse.processing.org/t/how-to-cycle-between-two-colors-using-lerp/31370>\
**Category:** Coding Questions\
**Created:** [July 21, 2021, 8:01pm UTC](https://discourse.processing.org/t/how-to-cycle-between-two-colors-using-lerp/31370 "2021-07-21T20:01:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cottonchipper](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/cottonchipper/32/10594_2.png) [@cottonchipper](https://discourse.processing.org/u/cottonchipper)\
**Post date:** [July 21, 2021, 8:01pm UTC](https://discourse.processing.org/t/how-to-cycle-between-two-colors-using-lerp/31370/1 "2021-07-21T20:01:35Z")

</div>

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?

```auto
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](https://editor.p5js.org/cottonchipper/sketches/nCFjb2FfX)

---

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [July 21, 2021, 8:33pm UTC](https://discourse.processing.org/t/how-to-cycle-between-two-colors-using-lerp/31370/2 "2021-07-21T20:33:04Z")

</div>

```auto

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; 
}

```

---

<div class="post-metadata">

**Author:** ![cottonchipper](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/cottonchipper/32/10594_2.png) [@cottonchipper](https://discourse.processing.org/u/cottonchipper)\
**Post date:** [July 21, 2021, 8:37pm UTC](https://discourse.processing.org/t/how-to-cycle-between-two-colors-using-lerp/31370/3 "2021-07-21T20:37:12Z")

</div>

Thank you so much for your help!
