Algorithm - locating enough space to draw a rectangle given the x and y axis of all other rectangles

Viewed 1563

Every rectangle has x and y coordinates, width and height.

The total width of the screen is maxWidth and total height is maxHeight.

I have an array containing all the already drawn rectangles.

I am working on an web App where users will be drawing rectangles on the screen using their mouse. For that I am using Javascript to draw on the canvas element.

The challenge is that the rectangles must not intersect at any given point.

I am trying to avoid this kind of case:

enter image description here

or this:

enter image description here

This is how the output I am aiming for should look like:

enter image description here

What I basically need is an Algorithm (preferably in JavaScript) that can help locating enough space to draw a rectangle knowing its axis, height and width.

3 Answers
Related