Search code examples
javascriptsvgsnap.svg

Snap.svg and dynamic text


I'm trying to place text dynamically into an svg created by Snap, this is what I tried:

this.setContent(
  `<svg id="${this.svgId}"></svg>`
);

var snap = Snap($(`#${this.svgId}`)[0]);
text = "asdfsdfsdsfd";

var rect = snap.paper.rect(0, 0, 50, text.length*3 + 4, 10);
snap.text(1.5,10, text);

console.log("rect", rect);
console.log("snap", snap);

rect.attr({
  fill: "#FFFFFF",
  fillOpacity: 0.6,
});

I get this: enter image description here

I want the rectangle to be just a little bigger than the text, but there must be a better way to do it than to calculate the length and height of the text, and that's assuming the font size won't change.

This is the only result I found regarding text in the snap docs: http://snapsvg.io/docs/#Paper.text


Solution

  • You could try using getBBox() on the text element, and use that to figure the size of the rect. getBBox() wll give you the x,y,width,height,x2,y2 figures to help.

    var text = s.text(0,0,'blah blah')
    var bb = text.getBBox();
    var rect = s.rect(bb.x, bb.y, bb.width, bb.height )
    

    Adjusting with offsets for whatever padding etc that you want. You may also need to allow for stroke widths, as I don't think that's included.