Fade out effect for text in HTML5 canvas

I draw plain text in an HTML5 canvas using this:

context.fillStyle = "#FF0000" context.font = "italic 20pt Arial"; context.fillText("sfddsfs", 50, 50); 

Now I want to animate to disappear from this text. How can I do that?

Edit: I know that there is currently no ready-to-use way to do this (at least I can't find anything). I am noob in graphic programming, but I want to study, so any hint about where to start is appreciated.

Maybe something like putting text in your own canvas and changing globalAlpha on the canvas ...? But the canvas background should be transparent. And I don’t know about performance, there are many small shortcuts appearing and disappearing everywhere that need to fade away.

+8
javascript html5 canvas effects
source share
3 answers

This is easier if you use rgba () notation to set fillStyle, rather than hexadecimal notation. Here is a working example ( demo ):

 // Create a canvas element and append it to <body> var canvas = document.createElement('canvas'), context = canvas.getContext('2d'); document.body.appendChild(canvas); function fadeOut(text) { var alpha = 1.0, // full opacity interval = setInterval(function () { canvas.width = canvas.width; // Clears the canvas context.fillStyle = "rgba(255, 0, 0, " + alpha + ")"; context.font = "italic 20pt Arial"; context.fillText(text, 50, 50); alpha = alpha - 0.05; // decrease opacity (fade out) if (alpha < 0) { canvas.width = canvas.width; clearInterval(interval); } }, 50); } fadeOut('sfddsfs');​ 
+13
source share

There is no built-in solution for this. You have to make an animation (fade), drawing each frame individually:

Set up some synchronization function that calculates the gradient between # FF0000 and the background color and redraws the text again and again until the background color is reached.

0
source share

I think I get it. I forgot to mention that I already have a rendering cycle and text objects that draw every frame on the frame.

So, the solution is to add an alpha variable to text objects:

 this.alpha = 1; 

and each x frame or time slightly reduces this.

and in the rendering loop:

 context.globalAlpha = textObject.alpha; //draw the text context.globalAlpha = 1; 
0
source share

All Articles