TAGS :Viewed: 12 - Published at: a few seconds ago

[ How to center text in the rectangle in svg.js? ]

I'm trying to draw a rectangle with a text centered in it while having the elements grouped. Here my code:

var draw = SVG('canvas')
var group = draw.group();

var rect = draw.rect(100,100).fill('#f09')
group.add(rect);

var text = draw.text('AAA');
text.font({anchor: 'middle', size: 30, family: 'Helvetica'});
text.move(50,50);

group.add(text);
group.move(100,100);

JSFiddle: http://jsfiddle.net/Lqw7n/2/

The result makes no sense for me.

Answer 1


I think its because you are moving the text but haven't really initially positioned it where you think. So its taking a default of 0,0 then you set anchor middle so half is off the screen, and then you moved it. However if you set its x,y first with the attr, it should work ok..

var group = draw.group();

var rect = draw.rect(100,100).fill('#f09')
group.add(rect);

var text = draw.text('AAA').attr({x:50, y:50 });
text.font({anchor: 'middle', size: 30, family: 'Helvetica'});
group.add(text);
group.move(100,100);

updated jsfiddle here http://jsfiddle.net/Lqw7n/5/