Search code examples
javascriptsvg.js

Undefined Text positioning SVG js v3


There are 2 cases with undefined behaviors of Text object positioning.

First Case

For example I want to position Rect at (50, 30) and Text at (0, 30) coordinates.

var draw = SVG().addTo('#app')

var rect = draw.rect(10, 10)
rect.move(50, 30)

var text = draw.text("Text")
text.move(0, 30)

I expect them to be at the same level y=30, but somehow there is +15 constant for Text object case 1 demo

Second Case

On my main app, I use Vue. So when I am trying to restore my system state, I use mounted() function.

mounted()
{
    let svg = SVG()
      .size(10000, 10000)
      .addTo('#flowchart-svg')

    let text =svg.text("H")
    text.move(100, 100)
    text.move(100, 100)

    let rect = svg.rect(10, 10)
    rect.move(100, 100)
    rect.move(100, 100)
}

Here the game begins: case 2 demo We can notice that Text position for both coordinates is summed and constant +15 disappeared for the Y coordinate. Expected result for me is to have Rect and Text on the same Y coordinate - 100.

+15 constant can be explained, maybe it is Text length, but on html page it is usually 18px instead of 15, but still it may be the case.

I have been trying to use .plain() instead of text(), but it didn't help.

Looking forward for explanation of those mysteries. Please let me know at the comments, if you think it is a bug of the SVG js library!

--Edit 1

Sorry, forgot to share here is my fiddle.


Solution

  • Svg.js uses the upper left edge of the bounding box to position elements (including text). Since svg positions text by its baseline, there is an offset. If you instead want to position text by its baseline, use amove (for anchor move) instead which will just set the x and y attributes as is