canvas: wait between line strokes / js sleep() - Javascript Canvas

Javascript examples for Canvas:Line

Description

canvas: wait between line strokes / js sleep()

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.7.1.js"></script> 
      <style id="compiled-css" type="text/css">

canvas{/* w  ww  .ja  v a2 s .c  om*/
   border: 1px solid black;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var lines = [
    [{x:20, y:20}, {x:60, y:40}, {x:80, y:10}, {x:120, y:70}, {x:180, y:30}],
    [{x:40, y:50}, {x:70, y:80}, {x:90, y:120}, {x:120, y:320}, {x:220, y:80}],
    [{x:20, y:230}, {x:70, y:80}, {x:30, y:80}, {x:10, y:80}, {x:10, y:40}],
    [{x:120, y:120}, {x:50, y:90}, {x:70, y:20}, {x:60, y:90}, {x:20, y:20}], ];
var can = document.getElementById("jsonCanvas");
var cxt = can.getContext('2d');
var lineCount = -1;
var pointCount = 0;
var intervalID;
cxt.beginPath();
cxt.strokeStyle = "ff0000";
nextLine(cxt);
function nextLine(cxt) {
    lineCount++;
    if(lineCount == lines.length){
       console.log(lineCount + " lines drawn");
       return;
    }
    pointCount = 0;
    cxt.moveTo(0, 0);
    intervalID = setInterval(drawLine, 200, cxt);
}
function drawLine(context) {
    var point = lines[lineCount][pointCount];
    console.log(lineCount, pointCount, point.x, point.y);
    context.lineTo(point.x, point.y);
    context.stroke();
    pointCount++;
    if (pointCount == lines[lineCount].length) {
        clearInterval(intervalID);
        nextLine(context);
    }
}
    });

      </script> 
   </head> 
   <body> 
      <canvas id="jsonCanvas" width="300" height="400"></canvas>  
   </body>
</html>

Related Tutorials