Rectangle fun

by Edward

HTML

Overlap (px^2): <span id="overlap">0</span ><br/>
Rect 1 (l,t,r,b): <span id="rect1"></span ><br/>
Rect 2 (l,t,r,b): <span id="rect2"></span ><br/>
Intersection (l,t,r,b): <span id="intersection"></span ><br/>

<div class="tester"></div>
<div class="tester"></div>

CSS

.tester {border:1px solid black;width:50px;height:50px}

JavaScript

function Rect(l, t, r, b) {
    this.l = l;
    this.t = t;
    this.r = r;
    this.b = b;
}
Rect.prototype.toString = function() {
    return "("+this.l.toString() 
            +","+this.t.toString()
            +","+this.r.toString()
            +","+this.b.toString()
            +") = ("+this.width().toString()
            +","+this.height().toString()+")";
};
Rect.prototype.width = function() {
    return this.r - this.l;
};
Rect.prototype.height = function() {
    return this.b - this.t;
};
Rect.prototype.intersectionArea = function(o) {
    x_overlap = Math.max(0, Math.min(this.r, o.r) - Math.max(this.l,o.l))
    y_overlap = Math.max(0, Math.min(this.b, o.b) - Math.max(this.t,o.t));
    return x_overlap * y_overlap;
};
Rect.prototype.intersection = function(o) {
    n = new Rect(
            Math.max(this.l,o.l),
            Math.max(this.t,o.t),
            Math.min(this.r,o.r),
            Math.min(this.b,o.b));
    if (n.width() <=0 || n.height() <= 0)
        return new Rect(0,0,0,0);
    return n;
};
var divs = $('.tester').resizable().draggable({
    drag: function(){
        var d0 = divs.eq(0).position(),
            d1 = divs.eq(1).position(),
            x11 = d0.left,
            y11 = d0.top,
            x12 = d0.left + divs.eq(0).width(),
            y12 = d0.top + divs.eq(0).height(),
            x21 = d1.left,
            y21 = d1.top,
            x22 = d1.left + divs.eq(1).width(),
            y22 = d1.top + divs.eq(1).height(),
            R1 = new Rect(x11, y11, x12, y12),
            R2 = new Rect(x21, y21, x22, y22);

        $('#rect1').text(R1.toString());
        $('#rect2').text(R2.toString());
        $('#overlap').text( R1.intersectionArea(R2) );
        $('#intersection').text( R1.intersection(R2).toString() );
    }
});