Text fade in fade out effect in HTML5

The following code example shows the text fade in and fade out effect on the canvas in HTMl5.

For this effect we are using the rgb values to set the fillStyle of the text. The program increase the rgb values for the fade-out effect
and decrease the rgb values for the fade-in effect. See the Demo.

  1. <html>
  2. <head>
  3.     <title>Text fade in – fade out Animation</title>
  4.     <style>
  5.         canvas{border: 1px solid #bbb;}
  6.         .subdiv{width: 320px;}
  7.         .text{margin: auto; width: 290px;}
  8.     </style>
  9.  
  10.     <script type="text/javascript">
  11.         var can, ctx, step = 50, steps = 255;
  12.               delay = 20;
  13.               var rgbstep = 50;
  14.  
  15.         function init() {
  16.             can = document.getElementById("MyCanvas1");
  17.             ctx= can.getContext("2d");
  18.             ctx.fillStyle = "blue";
  19.             ctx.font = "40pt Helvetica";
  20.             ctx.textAlign = "center";
  21.             ctx.textBaseline = "middle";
  22.                      Textfadeup();        }
  23.  
  24.           function Textfadeup() {
  25.             rgbstep++;
  26.             ctx.clearRect(0, 0, can.width, can.height);
  27.             ctx.fillStyle = "rgb(" + rgbstep + "," + rgbstep + "," + rgbstep + ")"
  28.             ctx.fillText("WELCOME", 150, 100);
  29.             if (rgbstep < 255)
  30.                 var t = setTimeout('Textfadeup()', 10);
  31.             if (rgbstep == 255) {
  32.                 Textfadedown();
  33.             }
  34.         }
  35.         function Textfadedown() {
  36. rgbstep=rgbstep-1;
  37.             ctx.clearRect(0, 0, can.width, can.height);
  38.             ctx.fillStyle = "rgb(" + rgbstep + "," + rgbstep + "," + rgbstep + ")"
  39.             ctx.fillText("WELCOME", 150, 100);
  40.             if (rgbstep > 80)
  41.                 var t = setTimeout('Textfadedown()', 10);
  42.             if (rgbstep == 80) {
  43.                 Textfadeup();
  44.             }
  45.         }  
  46.     </script>
  47.  
  48. </head>
  49. <body onload="init();">
  50.     <div class="subdiv">
  51.         <canvas id="MyCanvas1" width="300" height="200">
  52.   This browser or document mode doesn't support canvas object</canvas>
  53.           </div>
  54. </body>
  55. </html>

facebooktwittergoogle_plusredditpinterestlinkedinmail

2 thoughts on “Text fade in fade out effect in HTML5”

  1. I’ve tried doing this by copying and pasting your code into notepad and all I get is a black box, any ideas what I might be doing wrong ?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>