Drawing the Text

Finally, we draw the text to the Canvas, and the drawScreen() function is complete. In 20 milliseconds, drawScreen() will be called again, the alpha value will be updated, and the text will be redrawn:

    context.font         = "72px Sans-Serif";
    context.textBaseline = "top";
    context.fillStyle    = "#FFFFFF";
    context.fillText  (text, 150,200);
}

The full code for this example is as follows:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH1EX5 : Hello World Animated </title>
<script src="modernizr.js"></script>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);

function eventWindowLoaded () {
    canvasApp();
}

function canvasSupport () {
      return Modernizr.canvas;
}

function canvasApp () {

          if (!canvasSupport()) {
             return;
          }

        var theCanvas = document.getElementById("canvasOne");
        var context = theCanvas.getContext("2d");

          function drawScreen() {
            //background
            context.globalAlpha = 1;
            context.fillStyle = "#000000";
              context.fillRect(0, 0, 640, 480);
            //image
            context.globalAlpha = .25;
            context.drawImage(helloWorldImage, 0, 0);


            if (fadeIn) {
                alpha += .01;
                if (alpha >= 1)  {
                    alpha = 1;
                    fadeIn = false;
                }
            } else {
                alpha -= .01;
                if (alpha < 0)  {
                    alpha = 0;
                    fadeIn = true;
                }
            }

            //text
            context.font         = "72px Sans-Serif";
            context.textBaseline = "top";


            context.globalAlpha = alpha;
            context.fillStyle    = "#FFFFFF";
            context.fillText  (text, 150,200);

        }

        var text = "Hello World";
        var alpha = 0;
        var fadeIn = true;
        //image
        var helloWorldImage = new Image

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.