Fabric JS make all objects gravitate toward the center of the canvas

Solution for Fabric JS make all objects gravitate toward the center of the canvas
is Given Below:

I am looking for an algorithm that take a canvas as its input and makes all the objects in the canvas (currently only rectangular images) gravitate towards the center of the canvas, without colliding into each other. I am currently developing such an algorithm but I have encountered a few problems.

This is my current algorithm:

  1. Spread out all the objects on the canvas until no objects longer collide i.e. (obj1.isContainedWithinObject(obj) || obj1.intersectsWithObject(obj) || obj1.isContainedWithinObject(obj)) is false for every object pair
  2. Choose one object at a time and make that object move towards the center of the canvas one pixel at a time, and stop as soon as a collision is detected. When an object is stopped, do the same thing with the next object in the loop, until the loop runs out of objects.

I have just started on the second step on this algorithm, but I have the feeling there should be an easier way.

I attach images of the result of my attempts below:

Before:


enter image description here

After:


enter image description here