0

I've written this code

ctx.font = "25px Open Sans";
ctx.fillStyle = "white";
ctx.fillText(continue_msg, width/2-ctx.measureText(continue_msg).width/2, height/2.2);

And I'd like to know if its possible to create a rainbow text which will be smoothly changing colors from r to g to b back to r and repeat?

strangereu
  • 81
  • 1
  • 8
  • 2
    You can create a linear gradient, as per http://stackoverflow.com/questions/29007257/creating-a-rainbow-effect-in-rectangle-canvas – Evan Knowles Jan 11 '16 at 11:31
  • @EvanKnowles. As I read the question, they want the text to have a single fill color (rather than a gradient) but to animate that single color through the R,G,B range. I could be wrong. :-// – markE Jan 11 '16 at 17:53

1 Answers1

0

You can use the HSL color format to fill your text

HSL lets you focus on the Hue (Hue==color) of your fill and make the color change through the R,G,B color range.

You specify fill using HSL like this: ctx.fillStyle='hsl(255,100%,50%)'. The first value in HSL is the hue and you can vary the hue using integers from 0 to 255.

Here's example code and a demo that animates the text hue through R,G,B and back again:

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

ctx.font='25px Verdana';

var hue=0;
var direction=1;

requestAnimationFrame(animate);

function animate(time){
  ctx.fillStyle='black';
  ctx.fillRect(0,0,cw,ch);
  ctx.fillStyle='hsl('+hue+',100%,50%)';
  ctx.fillText('Use the Hue!',50,75);    
  requestAnimationFrame(animate);
  hue+=direction;
  if(hue>255){direction*=-1;hue=255;}
  if(hue<0){direction*=-1;hue=0;}
}
<canvas id="canvas" width=300 height=300></canvas>
markE
  • 102,905
  • 11
  • 164
  • 176