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.