Canvas How to - Display a new number every second








Question

We would like to know how to display a new number every second.

Answer


<!--from   w  w w.  j  a  va 2  s  . c  o m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "18px verdana";
window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || 
           window.webkitRequestAnimationFrame || 
           window.mozRequestAnimationFrame || 
           window.oRequestAnimationFrame || 
           window.msRequestAnimationFrame || 
     function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };
})();
var aNewNumber = 10;
var fps = 1;
function animate() {
    setTimeout(function () {
        requestAnimationFrame(animate);
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillText("Next number is: " + aNewNumber++, 50, 50);
    }, 1000 / fps);
}
animate();
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width=300 height=100></canvas>
</body>
</html>

The code above is rendered as follows: