Wesley Skeen
Wesley Skeen

Reputation: 8285

Html5 Canvas Smoothly transition from one color to another

Is there a way to smoothly transition from one color to another? For example blue to red.

I have an array that will loop around 125 times.

Within this array I want to transition a color from blue to red.

Will I have to have 125 different color values in its own array and then pick each one as the index loops through?

Upvotes: 0

Views: 1961

Answers (2)

Don Cowan
Don Cowan

Reputation: 1

You could also use separate, overlay canvases, one with the blue color and the other with red.

You could then change the transparency (global alpha) of each canvas over time in your animation function so that one canvas goes to 0 and the other goes to 100 percent transparency.

This canvas example darkens the sky over time:

http://marketimpacts.squarespace.com/storage/9781118385357%20ls1201%20Fireworks%20Display.htm

This is a code fragment from the example:

// F1. SUNSET increment & check for change.
skyInterval = sunset*sunsetFactor;
skyCount    = skyCount + interval;
if(skyCount > skyInterval) 
{
  // F2. SKY ALPHA increase if reached skyInterval.
  skyAlpha = skyAlpha + .01;
  if(skyAlpha > 1) {skyApha = 1}
  skyCount = 0;

  // F3. SKY alpha setting.
  contextSK.globalAlpha = skyAlpha;
  if(skyNight == 1) {contextSK.globalAlpha = 1}

  // F4. SKY gradient.
  var skyGrad = contextSK.createLinearGradient(0, 0, 0, canvasSK.height-sunsetHorizon);
  skyGrad.addColorStop( 0, "black");
  skyGrad.addColorStop(.8, "black");
  skyGrad.addColorStop( 1, "transparent");

  // F5. SKY fill.
  contextSK.fillStyle = skyGrad;
  contextSK.clearRect(0, 0, canvasSK.width, canvasSK.height);
  contextSK.fillRect( 0, 0, canvasSK.width, canvasSK.height);
}

Upvotes: 0

Pleyano
Pleyano

Reputation: 26

Use hsl instead of rgb or hexadecimal code. You will only need to change the first parameter of the function, which is the Hue and has an integer value.

Upvotes: 1

Related Questions