title: Algorithm - locating enough space to draw a rectangle given the x and y axis of all other rectangles
body: <p>Every rectangle has x and y coordinates, width and height.</p>
  
  <p>The total width of the screen is maxWidth and total height is maxHeight.</p>
  
  <p>I have an array containing all the already drawn rectangles.</p>
  
  <p>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.</p>
  
  <p>The challenge is that the rectangles must not intersect at any given point.</p>
  
  <p>I am trying to avoid this kind of case:</p>
  
  <p><a href="https://i.stack.imgur.com/DTuNe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DTuNe.png" alt="enter image description here"></a></p>
  
  <p>or this:</p>
  
  <p><a href="https://i.stack.imgur.com/IPIrF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IPIrF.png" alt="enter image description here"></a></p>
  
  <p>This is how the output I am aiming for should look like:</p>
  
  <p><a href="https://i.stack.imgur.com/ttq04.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ttq04.png" alt="enter image description here"></a></p>
  
  <p>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.</p>