I am in need of dynamically creating multiple text elements based on provided data. These text elements should be enclosed within a rectangle that matches the width of the text element with the largest width, similar to this example:
https://i.sstatic.net/U1ofR.png
Currently, I am utilizing a method to generate the text node, which appears as follows:
let textnodes = data.map(d => {
let svgText = document.createElementNS(d3.namespaces['svg'],'text')
let textNode = document.createTextNode(d.text)
svgText.appendChild(textNode)
return svgText
})
Subsequently, I calculate the width and then apply a maximum function, employing my custom getTextWidth
method:
Math.max(...textnodes.map(t=> {
return t.firstChild ? this.getTextWidth(
t.firstChild.nodeValue,
this.config.attributesFontSize + "px " + this.config.attributesFont ) : 0
}))
My query is: Is there any way to instantiate a SVGTextElement
as a type from D3 rather than using document.createElementNS(...)
? My reason for asking is that the use of SVGTextElement
would allow me to utilize the getBBox()
method, providing the width
property automatically. Ideally, I would like to create my text nodes in the following manner:
data.map({ d =>
let text = new SVGTextElement()
text.setAttribute(...)
...
})
Unfortunately, directly using the constructor in this way is not permitted.