beelzebub
beelzebub

Reputation: 43

fabric make group stay at same position

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

// Add some example shapes
var circle = new fabric.Circle({
  radius: 20, fill: 'green', left: 100, top: 100
});
var triangle = new fabric.Triangle({
  width: 20, height: 30, fill: 'blue', left: 50, top: 50
});

canvas.add(circle, triangle);

// Add some example text
var text1 = new fabric.Text('hello world', { left: 100, top: 100 });

var text2 = new fabric.Text('test', { left: 0, top: 0 });

canvas.add(text1, text2);

// Select all objects
function selectAllCanvasObjects(){
    var objs = canvas.getObjects().filter(function(o) {
        if (o.get('type') === 'text') {
            return o.set('active', true);
        }
    });

    var group = new fabric.Group(objs, {
        originX: 'center', 
        originY: 'center'
    });

    canvas._activeObject = null;

    canvas.setActiveGroup(group.setCoords()).renderAll();
}

$(document).on('click', '#change-btn', function(event){
selectAllCanvasObjects();
})

my intention when i click the button , it will select all the text object in canvas , which i got help from friend and got it done , but problem now is i want the set this function to button , but when i click the button multiple time the group position jump , how do i make the group position stay at the same spot ?

Demo here https://jsfiddle.net/Tedeee/9m2oxcj6/

Upvotes: 3

Views: 455

Answers (1)

Tim Harker
Tim Harker

Reputation: 2407

This should fix it (I added canvas.discardActiveGroup() to the top of your function):

// Select all text objects
function selectAllCanvasObjects(){
    canvas.discardActiveGroup();

    var objs = canvas.getObjects('text').filter(function(o) {
        return o.set('active', true);
    });

    var group = new fabric.Group(objs, {
        originX: 'center', 
        originY: 'center'
    });

    canvas._activeObject = null;

    canvas.setActiveGroup(group.setCoords()).renderAll();
}

(and I also cleaned up getObjects() as you can pass a string to get your 'text' objects)

Here's your JSFiddle updated, https://jsfiddle.net/rekrah/9m2oxcj6/2/.

Hope that helps, let me know if you have any other questions.

Upvotes: 1

Related Questions