I need to instantiate several text elements programmatically from given data.
These text elements should be surrounded by a rectangle that has the width of the text element with the largest width. Like this:
Now at the moment I am using a method to create the textnode, that looks like this:
let textnodes = data.map(d => {
let svgText = document.createElementNS(d3.namespaces['svg'],'text')
let textNode = document.createTextNode(d.text)
svgText.appendChild(textNode)
return svgText
})
and then I compute the width like this and finally apply a maximum function, where getTextWidth
is a self-made method :
Math.max(...textnodes.map(t=> {
return t.firstChild ? this.getTextWidth(
t.firstChild.nodeValue,
this.config.attributesFontSize + "px " + this.config.attributesFont ) : 0
}))
My question now is: Is there a way to create a SVGTextElement
instead of using document.createElementNS(...)
? The reason I am asking is, that SVGTextElement
gives me the possibility to use the getBBox()
method that gives me the width
property for free. Ideally I would like to instantiate my text nodes like this:
data.map({ d =>
let text = new SVGTextElement()
text.setAttribute(...)
...
})
However using the constructor like this is permitted.