canvas005

HTML

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

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x=20,y=20,speedX=4,speedY=3;
setTimeout(function(){
    if(x>400 || x<0){
     speedX = speedX*-1;   
    }
    if(y>400 || y<0){
     speedY = speedY*-1;   
    }
    ctx.clearRect(0,0,500,500);
    ctx.fillRect(x,y,100,100);
    x += speedX;
    y += speedY;
    setTimeout(arguments.callee, 20);
},1);