canvas005

HTML

<canvas width="500" height="500" id="canvas"></canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var i=0,speed=5;
setTimeout(function(){
    if(i>400){
     speed=-50;   
    }else if(i<0){
        speed=5;
        }
    ctx.clearRect(0,0,500,500);
    ctx.fillRect(i,0,100,100);
    i += speed;
    setTimeout(arguments.callee, 20);
},1);