-1

I was looking for the javascript equivalent of the CoreGraphics function of CGRectUnion. I found isPointInPath. I was reading about clip paths so thought this was very much a possibility.

What this function does is take two rectangles.

function CGRectUnion(rect1, rect2) {

}

Each rect object has 4 keys, w, h, x, and y. x and y is the top left coordinate of the rectangle and w and h are the width and height.

The function returns false if no portion of rect2 overlaps rect1. If rect2 overlaps rect1 it then returns a rectangle object of the common area between the two rectangles.

Is there a built in function like this in javascript, especially canvas related area?

Thanks

Noitidart
  • 35,443
  • 37
  • 154
  • 323
  • A. No, there isn't a build in funcyion for this. B. Really??? – Amit Jul 23 '15 at 06:08
  • @Amit I felt this was a possibility as I found function `isPointInPath`. This rect function seems like a common thing to do when working with bitmaps. I was reading about `clip` paths so thought this was very much a possibility. – Noitidart Jul 23 '15 at 06:09
  • 1
    That's because there's at least some sophisticated logic in it. A path can be a complex shape, and it's not trivail to know if a point is inside or not. What you're asking is much more trivial and much more isoteric. A 2 rect intersection is a trivial mathematic task that you should be capabale of handling with a few lines of code at the most. – Amit Jul 23 '15 at 06:12
  • Well you'll have to excuse me, it's a built in function in CoreGraphis library, and other bitmap libraries I have used, I thought it was a possibility. For example: http://mdn.beonex.com/en/JavaScript_code_modules/Geometry.jsm/Rect.html – Noitidart Jul 23 '15 at 06:16

1 Answers1

1

I haven't heard of a function like that for canvas, however it's a pretty simple function so you can just implement it yourself like this:

function CGRectUnion(r1, r2) {
    var rightEdge1 = r1.x+r1.w;
    var rightEdge2 = r2.x+r2.w;
    var bottomEdge1 = r1.y+r1.h;
    var bottomEdge2 = r2.y+r2.h;

    // first check if the rectangles overlap at all, if not return false
    if(r1.x > rightEdge2 || rightEdge1 < r2.x || r1.y > bottomEdge2 || bottomEdge1 < r2.y) {
        return false;
    }

    // return a new rectangle for the intersection
    return {
        x: Math.max(r1.x, r2.x),
        y: Math.max(r1.y, r2.y),
        w: Math.min(rightEdge1, rightEdge2) - Math.max(r1.x, r2.x),
        h: Math.min(bottomEdge1, bottomEdge2) - Math.max(r1.y, r2.y)
    };
}

A demo can be found here: http://jsfiddle.net/zfaqrnth/

Sebastian Nette
  • 7,364
  • 2
  • 17
  • 17
  • Thanks very much @Sebastian I actually hit jackpot with this link here, its all javascript, its in a jsm file so i just took it out: http://mdn.beonex.com/en/JavaScript_code_modules/Geometry.jsm/Rect.html – Noitidart Jul 23 '15 at 08:31