Fabric JS父子对象

时间:2015-05-08 22:27:31

标签: javascript html5 canvas fabricjs

我正在尝试将面料JS用于座位表应用程序。我有平面图和每个用户的单独对象。我可以将它们彼此独立地移动。我希望用户成为平面图的父级,这样当我移动平面图对象时,所有用户都会随之移动。有没有办法用布料做到这一点?

1 个答案:

答案 0 :(得分:1)

找到了办法;虽然我仍然想知道结构框架是否有办法自动处理这个问题而不是自己为所有父子关系创建它。

// Create canvas
canvas = new fabric.Canvas('c');
img = document.getElementById("cur_image");

// Create parent object
background = new fabric.Image(img, {
    left: 0,
    top: 0,
    angle: 0,
    opacity: 1.0
});
canvas.add(background);

// Connect move handler that will move the children
background.on('moving', backgroundMoveHandler);

children = [];
function addItem() {
    var rect = new fabric.Rect({
        left: 100,
        top: 100,
        fill: 'red',
        width: 50,
        height: 50
    });
    canvas.add(rect);
    children.push(rect);
}

// Add some children
addItem();
addItem();

// Whenever the parent is moved, move the children as well.
function backgroundMoveHandler(options) {
    var x = options.e.movementX;
    var y = options.e.movementY;
    $.each(children, function(i, obj) {
        obj.set('left', obj.left + x);
        obj.set('top', obj.top + y);
        obj.setCoords();
    });
}