FabricJS:始终在画布上居中对象 [英] FabricJS: Always Center Object on Canvas

查看:1911
本文介绍了FabricJS:始终在画布上居中对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将一个对象集中在fabricjs画布上?

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

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

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?

关心并感谢
Robert

Regards and Thanks Robert

推荐答案

Fabric对象具有以下聚类方法:

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.

以下内容可能会起作用

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

});

这篇关于FabricJS:始终在画布上居中对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆