FabricJS: Always Center Object on Canvas

后端 未结 2 1595
滥情空心
滥情空心 2021-02-05 22:27

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 wan

相关标签:
2条回答
  • 2021-02-05 22:44

    Fabric objects have the following methods for centering:

    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
    

    I don't see anything about offset in the docs.

    Something like the following would probably work

    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();
    
    });
    
    0 讨论(0)
  • 2021-02-05 22:53

    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();
    
    0 讨论(0)
提交回复
热议问题