Canvas How to - Move rectangle along horizontal line








Question

We would like to know how to move rectangle along horizontal line.

Answer


<!--from   w  ww  . j  av a 2 s  . c  om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var x = 0;
    var y = 50;
    var width = 10;
    var height = 10;
    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillRect(x, y, width, height);
        x++;
        if(x <= 490) {
            setTimeout(animate, 33);
        }
    }
    animate();
}
</script>
</head>
<body>
  <canvas id="canvas" width="500" height="400"
    style="border: 1px solid #000000;"></canvas>
</body>
</html>

The code above is rendered as follows: