Canvas AABB demo.

by razh

HTML

<canvas id="canvas"></canvas>

CSS

body {
    margin: 0;
}

#canvas {
    background-color: black;
}

JavaScript

function Rect(x, y, width, height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.fill = 'white';
}

Rect.prototype.draw = function(ctx) {
    ctx.fillStyle = this.fill;
    ctx.fillRect(this.x, this.y, this.width, this.height);
};

Rect.prototype.intersectsWith = function(rect) {
    // Inequalities to determine if this rectangle is inside another rectangle.
    if (this.x + this.width < rect.x) return false;
    if (this.y + this.height < rect.y) return false;
    if (this.x > rect.x + rect.width) return false;
    if (this.y > rect.y + rect.height) return false;
    
    return true;
    
};

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

var canvasWidth = canvas.width,
    canvasHeight = canvas.height;

var enemies = [];

enemies.push(new Rect(20, 20, 30, 30));
enemies.push(new Rect(200, 100, 30, 30));
enemies.push(new Rect(40, 30, 30, 30));

function loop() {
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);

    for (var i = 0, il = enemies.length; i < il; i++) {
        var intersecting = false;
        for (var j = 0, jl = enemies.length; j < jl; j++) {
            // Make sure we're not checking the same two rectangles.
            if (i !== j) {
                intersecting = intersecting || enemies[i].intersectsWith(enemies[j]);
            }
        }
        
        // If we're intersecting, color it red.
        if (intersecting) {
            enemies[i].fill = 'red';
        } else {
            enemies[i].fill = 'white';
        }

        enemies[i].draw(ctx);
    }
    
    requestAnimationFrame(loop);
}

loop();