Fade out effect for text in HTML5 canvas

By | January 12, 2018

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.


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');

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;
        }, 50); 



There is no built-in solution to this. You have to do the animation(fade) by drawing each frame individually:

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


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;

Leave a Reply

Your email address will not be published. Required fields are marked *