How to Center an Object Within Another Object in Fabric JS

Learn how to center an object within another object in Fabric JS with just a few short methods.

How to Center an Object Within Another Object in Fabric JS

Fabric JS is all about manipulating objects. Objects can be moved, resized, added, deleted, and more. Usefully when adding an object, you will center it on the canvas, but sometimes, you might want to center it within another object. Luckily we have the code to do it. Here is how to center an object within another object in Fabric JS.

How to Center an Object Within Another Object in Fabric JS

Use the getCenterPoint() method with the setPositionByOrigin() method to center a Fabric JS object within another object. Let’s look at an example:

let centerPoint = objectA.getCenterPoint()

objectB.setPositionByOrigin(centerPoint, 'center', 'center')
      
    

First, we need to get the center point of the first object, Object A, in our example. To easily get the center point coordinates, we can use the built-in getCenterPoint() method. 

With the center point coordinates in hand, we must apply them to our second object, Object B. We can use the setPositionByOrigin() method to accomplish this. 

You can use the same code to center two objects to one another within a group. 

let circle = new fabric.Circle({
  radius: 200,
  fill: 'green'
})

let rect = new fabric.Rect({
  fill: 'red'
  width: 100,
  height: 200,
})

let group = new fabric.Group([circle, rect])
canvas.add(group)

let centerPoint = circle.getCenterPoint()
rect.setPositionByOrigin(centerPoint, 'center', 'center')
      
    

Objects within a group are bound to each other and will be moved and manipulated together.

How to Change Object Order in Fabric JS

To change the depth of an object, use the sendToBack() or sendBackwards() methods to push an object back. 

let rectA = new fabric.Rect({
  fill: 'green'
  width: 100,
  height: 200,
})

let rectB = new fabric.Rect({
  fill: 'red'
  width: 200,
  height: 400,
})

canvas.add(rectA)
canvas.add(rectB)

canvas.sendToBack(rectB)
      
    

Once you have centered your objects, depending on your use case, you might want to rearrange the order of the objects so one will overlap the other. 

To accomplish this, we have four different methods we can use:

canvas.sendBackwards(yourObj)
canvas.bringForward(yourObj)
canvas.sendToBack(yourObj)
canvas.bringToFront(yourObj)
      
    

These methods can be used either before or after you move your object initially. 

You now know how to center an object within another object and also change its order with Fabric JS. Although this may be for only specific-use cases, it is a valuable technique if you want to add unique overlays to our project. 

Check out our other Fabric JS guides, tips, and tricks in our Fabric JS Coding Section.