Question

I want to place the text in center of the rectangle based on the text width and height as well as rect width and height. Please refer the below SVG code.

<g transform="translate(73,535)" id="container_svg_ToolTip">
<rect id="container_svg_SvgRect" x="314.58333333333337" y="-85.60000000000001" width="16" height="16" fill="white" stroke-width="1" stroke="Black"/>
<text id="container_svg_ToolTipText_4" x="314.58333333333337" y="-85.60000000000001" fill="black" font-size="12px" font-family="Times New Roman" font-style="Normal " text-anchor="start" clip-path="url(#container_svg_ChartAreaClip)" dominant-baseline="middle">40
</text></g>

i want to set the rectangle width and height based on maximum text size (width and height) and then i want to place the text in center of the rectangle. need some calculation to do this.. no need to add padding value like rectX+10, rectY+10 like that in below link.

SVG: text inside rect

Please refer below screenshot.

enter image description here

Thanks,

Siva

Was it helpful?

Solution

This should work:

        var text = $("#my_svg #container_svg_ToolTipText_4");
        var width = text.innerWidth();
        var rect = $("#my_svg #container_svg_SvgRect");
        rect.attr("width", width + 10);

If you set the x value of the rect to be 5 units less than the x unit of the text, it will be centred. Set the y value of the rect to be ~10 units less than the y unit of the text or calculate the height of the text using innerHeight.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top