I am creating charts with d3.js+svg+javscript/typescript. I need to know length of texts to append it in proper places.
I am using/was trying to use functions getBBox() and getComputedTextLength(), but... getBBoX works only when I am generating chart for the first time (for second time and next it returns 0), while getComputedTextLength() works... just sometimes. From that what I read the problem could be that svgtext is not generated before I am trying to read its width/height.
export function ReturnWidthOfText(text1, rotate, fontSize, someSVGGroup , fontName)
{
var tempText;
if (rotate == true)
{
tempText = someSVGGroup.append("svg:text")
.attr("id", "lolo")
.style("font-size", fontSize + "px")
.style("font-family", fontName)
.attr("transform", "rotate(270)")
.text(text1);
}
else
{
tempText = someSVGGroup.append("svg:text")
.attr("id", "lolo")
.style("font-size", fontSize + "px")
.style("font-family", fontName)
.text(text1);
}
var width = tempText.getComputedTextLength();
document.getElementById("lolo").parentNode.removeChild(document.getElementById("lolo"))
return width;
}
export function ReturnSizeOfText(text1, rotate, fontSize, someSVGGroup, fontName) {
//let svgText = document.getElementById("lolo");
var tempText;
if (rotate == "Yes")
{
tempText = someSVGGroup.append("svg:text")
.attr("id", "lolo")
.style("font-size", fontSize + "px")
.style("font-family", fontName)
.attr("transform", "rotate(270)")
.text(text1);
}
else
{
tempText = someSVGGroup.append("svg:text")
.attr("id", "lolo")
.style("font-size", fontSize + "px")
.style("font-family", fontName)
.text(text1);
}
let size;
size = { Width: 0, Height: 0 };
let element: any = document.getElementById("lolo");
let bbox = element.getBBox();
//console.log(text.node().getBBox());
size.Width = bbox.width;
size.Height = bbox.height;
//var width = tempText.getComputedTextLength();
document.getElementById("lolo").parentNode.removeChild(document.getElementById("lolo"))
return size;
}
Could anyone advise how to improve those functions to work properly? As I am preparing "App for Office" I am interested mainly in solution for IE and Edge.
I've found an answer. It was returning 0s, because it returns good results only when svg/html block is visible, while when I was trying to regenerate chart it was hidden.