Rect object

by tmyie

HTML

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

JavaScript

function Rect(x, y, w, h, dltX, dltY, color) {

    var me = this;

    this.color = color || '#000';
    this.deltaX = dltX;
    this.deltaY = dltY;
    this.x = x;
    this.y = y;
    this.width = w;
    this.height = h;

    this.update = function(ctx) {
        me.x += me.deltaX;
        me.y += me.deltaY;

        ctx.fillStyle = this.color;
        ctx.fillRect(me.x, me.y, me.width, me.height);
    }

}

var ctx = canvas.getContext('2d'),
    rects = [
        new Rect(10, 10, 100, 100, 1, -2),
        new Rect(70, 200, 100, 100, 1, -2, '#900'),
        new Rect(50, 160, 80, 80, -1, 1, '#009'),
        new Rect(20, 190, 70, 70, 2, 3, '#090'),
        new Rect(100, 1, 50, 50, 2, 2, '#f90')
    ];
      
function loop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for(var i = 0, r; r = rects[i]; i++) {
        if (r.x < 0 || r.x > canvas.width - r.width) r.deltaX = -r.deltaX;
        if (r.y < 0 || r.y > canvas.height - r.height) r.deltaY = -r.deltaY;
        r.update(ctx); 
    }
    
    requestAnimationFrame(loop);
}
requestAnimationFrame(loop);