4

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.

atok
  • 5,880
  • 3
  • 33
  • 62

2 Answers2

3

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/

Ian
  • 13,724
  • 4
  • 52
  • 75
  • 1
    But it's still not centered vertically. I expect the anchor point to be below the text as described in https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor – atok Nov 06 '13 at 21:24
  • Ah sorry, thought you just meant horizontal. I suspect you may have to have a play with baseline-shift and dominant-baseline – Ian Nov 06 '13 at 22:32
  • there is no text in the rect in your fiddle – jorrebor Feb 16 '15 at 15:07
  • wow was a long time ago, there isn't on the original either, so something else looks amiss. I would post up a new question if its a similar issue. – Ian Feb 16 '15 at 15:17
1

instead of text.move you can use text.center like

<div id="canvas"></div>
<script type="text/javascript" src="svg.min.js"></script>
<script type="text/javascript">
var draw = SVG('canvas');

var group = draw.group();

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

var text = group.text('AAA')
.font({size: 30, family: 'Helvetica'})
.center(0.5*rect.width(), 0.5*rect.height());

group.move(100, 100);

</script>

i also replaced group.add with group.rect and group.text

source: https://github.com/svgdotjs/svg.js/issues/842#issuecomment-379554588

milahu
  • 2,447
  • 1
  • 18
  • 25