Canvas How to - Move rectangle from top to bottom








Question

We would like to know how to move rectangle from top to bottom.

Answer


<!--   www .j a  v  a  2 s .  c  o m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js' None></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    var canvas = document.getElementsByTagName('canvas')[0],
        ctx = canvas.getContext('2d'),
        curTop = 0,
        GOAL_TOP = 367;
    var renderRect = function () {
        curTop = curTop + ((GOAL_TOP - curTop) * 0.05);
        if (curTop > GOAL_TOP - 10) {
            curTop = 0;
        }
        ctx.clearRect(0, 0, 320, 417);
        ctx.fillStyle = 'rgb(255,0,0)';
        ctx.fillRect(0, curTop, 320, 50);
        setTimeout(renderRect, 16);
    }
    renderRect();
});//]]>  
</script>
</head>
<body>
  <canvas width="320" height="417"></canvas>
</body>
</html>

The code above is rendered as follows: