15

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

4

2 回答 2

35

或者您可以像这样将对象居中

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

    Canvas.setActiveObject(oImg);
    Canvas.renderAll();
于 2014-09-21T11:36:02.363 回答
22

Fabric 对象具有以下居中方法:

obj.center();  // Centers object vertically and horizontally on canvas to which is was added last
obj.centerV(); // Centers object vertically on canvas to which it was added last
obj.centerH(); // Centers object horizontally on canvas to which it was added last

我在文档中没有看到任何关于偏移的内容。

像下面这样的东西可能会起作用

var canvas = new fabric.Canvas('c');

$(window).resize(function(){

     var w = $(window).width();
     var h = $(window).height();
     var center = {x:w / 2, y:h / 2);

     canvas.setDimensions({width:w,height:h});
     canvas.forEachObject(function(obj){

        obj.set({
            left : center.x + obj.offsetLeft,
            top : center.y + + obj.offsetTop,
        });

        obj.setCoords();

    });

// need to call calcOffset whenever the canvas resizes
canvas.calcOffset();
canvas.renderAll();

});
于 2013-06-26T03:58:57.167 回答