Aligning image and text in a group object

Attempting to create a group object with an image and text object. It looks like an icon followed by text. Incorrect object alignment. I can manually set the left, top and adjust them, but the text, font, etc. May change at runtime.

When the font / text length changes, the alignment gets messed up again. Is there a way to ensure that the text always starts after the image (regardless of text length, font, etc.).

If there is no fabric built-in way to do this, is there a workaround? Here's the code I tried and the jsFiddle link below, you can see how the image and text overlap. Thank.

var canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('http://i.imgur.com/vews5Vd.jpg', function(img) {
    var img1 = img.scale(1).set({ left: 0, top: 0 });
    var text = new fabric.Text('the_text_sample', {
                fontFamily: 'Arial',
                fontSize:30,
                left:img1.width,
                top:10,

            });
    var group = new fabric.Group([ img1,text ], { left: 200, top: 200 });
    canvas.add(group);
});

      

http://jsfiddle.net/gCpnz/

+3


source to share


1 answer


You're close ... just make sure the text.top property is equal to half the image height + half-text height. Also with text.left.

After creating the text object, the width and height of the text can be obtained using text.getBoundingRectWidth () and text.getBoundingRectHeight ().

So your code will look like this:



var scaleFactor=1.0
var canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('http://i.imgur.com/vews5Vd.jpg', function(img) {
    var img1 = img.scale(scaleFactor).set({ left: 0, top: 0 });
    var text = new fabric.Text('the_text_sample', {
                fontFamily: 'Arial',
                fontSize:30,
            });
            text.set("top",img.height*scaleFactor/2+text.getBoundingRectHeight()/2);
            text.set("left",-img.width*scaleFactor/2+text.getBoundingRectWidth()/2);  

    var group = new fabric.Group([ img1,text ], { left: 200, top: 200 });
    canvas.add(group);
});

      

Here's the script:

http://jsfiddle.net/m1erickson/5Wzvg/

+4


source







All Articles