Thursday, 28 November 2013

// // Leave a Comment

SVG text in boxes with Snap.svg

SVG differs from the HTML5 that you're used to in lots of ways. One of which is text. One requirement I had was to create a box round an arbitrary length of text, like this:
That's pretty easy in a DIV with some CSS and it's not difficult in SVG, just different. We're going to use the Snap.SVG library to implement it.

The code

First we create the box, add some style. Then we create the text, then some style. Finally, we update the width of the box using the width of the text.

JSFiddle Live example.

Group to join together

The resulting SVG is just two elements that are happened to be one on top of the other. The text is not actually contained in the box, it's floating on top. Unlike a DIV, if you were to add drag functionality to the box, the text would remain exactly where it is. To do this, you need to use Snap to group the elements together. Then you can then assign the drag functionality to the group and it behaves normally.

Changing the length of the text

If you were to change the text in the box, you would need to manually update the width of the container too. DIV do that automatically with flow but you don't get that in SVG. If that kind of text flow is required, you might want to avoid SVG altogether and stick with a mix of HTML and SVG.