0

Need to "mark" a svg text item with a background color, it has to be generated with javascript.
Found a working method but it needs to code the text, get the bbox values and draws a rect at the text position. I can't use "fill-opacity" (the text/background need to be above other elements!) and with a solid colored rect the text isn't seen anymore.

With the idea "first element -> 'painted' first" or the last element will be seen, I rewrite the text element once more .. all is ok ... but is there a simpler method?

Roughly the code is this:

    var textColored = function (parent, text, idTxt, anchor, xT, yT, textColor, fillColor) {
    var labelText = $svg.text(idTxt,
        xT, yT,
        text, // "xTime.hh+":"+xTime.mm + " Sunset",
        {
            fill: textColor,
            "font-size": defaultOptions.fontSize,
            "text-anchor": anchor,
            "font-style": "italic"
        }
    )
    labelText.appendTo(parent);

    // background for text
    var bbox = $("#" + idTxt)[0].getBBox();
    var sRect = $svg.rect(
        // "x","y","width","height"
        bbox.x -2, bbox.y, bbox.width + 4, (+defaultOptions.fontSize + 3)
    )
        .attr("fill", fillColor)
//      .prependTo(parent);       // not working! added to first position of 'parent', see Inspector 
        .appendTo(parent);
    labelText.appendTo(parent);
}

Tried with the edited code to use '.prependTo' but that adds the background element to the top of 'parent' and so at lowest level - behind all other svg elements.
Also failed with <g> element as recommended by Robert failed (for the moment).
Probably will stay with the double adding the text element which works fine using scripting with bbox. As described the background size and position has to be 'generated' based on the text.

neandr
  • 209
  • 1
  • 3
  • 13
  • Not sure I understand. My problem is to get the right size for the background. With my example I get those values with the bbox.values. But only *after* the text element was build. – neandr Jan 06 '16 at 19:41
  • Use prependTo rather than appendTo for the background and then drop the last line. – Robert Longson Jan 06 '16 at 21:50
  • Sounds logical, but with my code it's not "at the top", so the idea with the background to draw above "other" svg text (painted before) will not work. At what "level" goes the background using "prependTo"? – neandr Jan 06 '16 at 22:52
  • Stick each text in it's own `` then they will all be at the "top" of that `` – Robert Longson Jan 07 '16 at 07:17
  • or do this http://stackoverflow.com/questions/12260370/draw-text-in-svg-but-remove-background#answer-12263962 – Robert Longson Jan 07 '16 at 07:55

0 Answers0