Canvas How to - Click to reset animation








Question

We would like to know how to click to reset animation.

Answer


<!--from w w  w  .  j a  v a2s.  c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d"),
        w = canvas.width,
        h = canvas.height;
    var currentX = 0;
    window.addEventListener("click", reset);
    function reset(){
        currentX = 0;
    }
    setInterval(redrawScreen, 10);
    function redrawScreen(){
        ctx.clearRect(0,0,w,h);
        ctx.fillRect(currentX,0,30,30);
        currentX = currentX + 1;
    }
}//]]>  
</script>
</head>
<body>
  <!DOCTYPE html>
<html>
<body>
  <canvas id="canvas" width="500" height="500" />
</body>
</html>

The code above is rendered as follows: