Displaying a loading spinner when drawing HTML5 canvas. - Javascript Canvas

Javascript examples for Canvas:Draw

Description

Displaying a loading spinner when drawing HTML5 canvas.

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){/*from w  ww  . j  a v a 2s  .co  m*/
image = new Image();
image.src = "https://upload.wikimedia.org/wikipedia/commons/1/1e/Large_Siamese_cat_tosses_a_mouse.jpg";
var canvas = document.getElementById('myCanvas-1');
var ctx = document.getElementById('myCanvas-1').getContext('2d');
var loading = true;
var loadingText = "Loading";
var event = new Event('loading');

canvas.addEventListener('loading', function (e) {
    setInterval(function () {
        if (loading) {
            console.log("update");
            ctx.fillStyle = "#FFF";
            ctx.fillRect(0, 0, 400, 400);
            ctx.font = '15pt Arial ';
            ctx.fillStyle = "#000";
            ctx.fillText(loadingText, 200, 200);
            if (loadingText == "Loading...") {
                loadingText = "Loading";
            }
            loadingText = loadingText + "."
        }
    }, 1);
}, false);
canvas.dispatchEvent(event);
setTimeout(function () {
    ctx.drawImage(image, 0, 0);
    ctx.font = '15pt Arial ';
    ctx.fillStyle = "#000";
    loading = false;
}, 5000);
    });

      </script> 
   </head> 
   <body> 
      <canvas id="myCanvas-1" width="400" height="400"></canvas>  
   </body>
</html>

Related Tutorials