Anthony
Anthony

Reputation: 671

transition on fillStyle color

I have a visualizer setup and it changes color every 7.5 seconds, problem is, it does it immediately, can you use .animate() on fillStyle? if not, is there any way to add a transition to fillStyle?

Upvotes: 1

Views: 3524

Answers (1)

markE
markE

Reputation: 105015

fillStyle does not have a method to automatically animate its transition.

However, its fairly easy to create an animation loop that animates the transition.

What you do is draw your frenzied content twice per frame in animation loops occuring over 2.50 seconds:

  • Draw with the starting color having an opacity that decreases over your 2.50 seconds.

  • Draw with the ending color having an opacity that increases over your 2.50 seconds.

Here's annotated example code and a Demo:

// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var duration=2.50;

// starting and ending colors
var rgbStart='#BC49FF';
var rgbEnd='#574FFF';
// calculate the # of frames that requestAnimationFrame can
// draw during the duration
var opacitySteps=parseInt(60*duration);
// set the current opacity step at its starting number (0)
var opacityStep=0;

// start the 2.5 second animation
requestAnimationFrame(animate);


function animate(time){

  // calculate the current opacity as a percentage
  //     of opacityStep/opacitySteps
  var opacity=100*(opacityStep/opacitySteps);
  if(opacityStep>=opacitySteps-1){ opacity=100; }

  // clear the canvas
  ctx.clearRect(0,0,cw,ch);

  // draw with the starting color using a lessening opacity
  ctx.globalAlpha=(100-opacity)/100;
  ctx.fillStyle=rgbStart;
  ctx.fillRect(20,20,100,75);
  ctx.strokeRect(20,20,100,75);

  // draw with the ending color using a increasing opacity
  ctx.globalAlpha=(opacity)/100;
  ctx.fillStyle=rgbEnd;
  ctx.fillRect(20,20,100,75);
  ctx.strokeRect(20,20,100,75);

  // clean up, reset globalAlpha to it's default of 1.00
  ctx.globalAlpha=1.00;

  // return if all steps have been played
  if(++opacityStep>=opacitySteps){return;}

  // otherwise request another frame
  requestAnimationFrame(animate);
}

$('#again').click(function(){
  opacityStep=0;
  requestAnimationFrame(animate);    
})
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Transitioning a fillStyle over 2.50 seconds</h4>
<br><button id=again>Again</button>
<br><canvas id="canvas" width=300 height=300></canvas>

Upvotes: 4

Related Questions