Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade out effect for text in HTML5 canvas

I'm drawing simple text in HTML5 canvas using this:

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

Now I want to animate fade out of this text. How can that be done?

Edit: I'm aware there's currently no ready to use way to do this (at least I can't find anything). I'm a noob in graphic programming but want to learn, so any hint about where to start is appreciated.

Maybe something like putting the text in an own canvas and changing globalAlpha of the canvas...? But the background of the canvas would have to be transparent. And don't know about performance, have a lot of small labels appearing and dissapearing everywhere which need to be faded out.

like image 410
User Avatar asked Mar 29 '12 20:03

User


2 Answers

It's easier if you use rgba() notation to set the fillStyle rather than the hexadecimal notation. Here's 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');
​
like image 55
Ori Avatar answered Sep 27 '22 21:09

Ori


I think I got it. Forgot to mention that I have already a render loop and text objects which draw themselves on the canvas each frame.

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

this.alpha = 1;

and each x frames or time reduce this a bit.

and in the render loop:

context.globalAlpha = textObject.alpha;
//draw the text
context.globalAlpha = 1;
like image 28
User Avatar answered Sep 27 '22 22:09

User