Canvas How to - Create character Typing in animation








Question

We would like to know how to create character Typing in animation.

Answer


<!-- w  w w .ja va  2  s.co  m-->

<!DOCTYPE html>
<html>
<body>
  <canvas id="myCanvas"></canvas>
  <script>
            var c = document.getElementById('myCanvas');
            var ctx = c.getContext('2d');
            ctx.fillStyle = "black";
            ctx.font = "30px sans-serif";
            var words = "Hello world!";
            var count = 0;
            var pause = 500; // ms to wait before drawing next character
            var chars;
            function draw() {
                count ++;
                // Grab all the characters up to count
                chars = words.substr(0, count);
                // Clear the canvas each time draw is called
                ctx.clearRect(0, 0, c.width, c.height);
                // Draw the characters to the canvas
                ctx.fillText(chars, 0, 150);
                if (count < words.length)
                    setTimeout(draw, pause);
            }
            draw();
        </script>
</body>
</html>

The code above is rendered as follows: