FabricJS: Always Center Object on Canvas

Robert picture Robert · Jun 24, 2013 · Viewed 22.9k times · Source

is it possible to ALWAYS center an object on a fabricjs canvas?

Background: I am building a webtool that makes it easy to create complex animations using fabricjs. I want to be able to set the canvas size to 100% for both width and height. Thus I want to place all my objects at the center and add an X/Y offset to it. When I resize the canvas later on I can readjust the objects from center using the x/y offset.

Is there such a build in function? Or should I simply add a property to the object and if the canvas is being resized - check all objects for that property and readjust the object's position from the new canvas' center?

Regards and Thanks Robert

Answer

Darryl Hebbes picture Darryl Hebbes · Sep 21, 2014

Or you can center the object like so

    // add the image object 
    Canvas.add(oImg)
    // set the object to be centered to the Canvas
    Canvas.centerObject(oImg);

    Canvas.setActiveObject(oImg);
    Canvas.renderAll();