Html FabricJS:始终在画布上居中对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17270168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:24:41  来源:igfitidea点击:

FabricJS: Always Center Object on Canvas

javascripthtmlhtml5-canvasfabricjs

提问by Robert

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

是否可以始终将对象放在 fabricjs 画布上?

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.

背景:我正在构建一个网络工具,可以轻松地使用fabricjs 创建复杂的动画。我希望能够将画布大小的宽度和高度都设置为 100%。因此,我想将所有对象放在中心并为其添加 X/Y 偏移。当我稍后调整画布大小时,我可以使用 x/y 偏移量从中心重新调整对象。

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

问候和感谢罗伯特

回答by Darryl Hebbes

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();

回答by cyberpantz

Fabric objects have the following methods for centering:

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

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();

});