javascript - Giving SVG text a background with rect -


i know has been asked here before i'm encountering weird issue...

i'm trying give arbitrarily sized text coloured background. i'm doing is: creating text, calculating coordinates , dimensions of text, , creating rectangle same dimensions , coordinates, ensuring it's inserted before text not cover up. i'm using d3 of this.

the issue rectangle slightly thin, text sticks out end (words ending in "s" seem main offender, weirdly). vertical placement of rectangles high, there's blank space @ top, , "dangling" letters g, p, etc. extend beneath rectangle.

see following image:

enter image description here

here's code i'm using:

let textcontainer = self.svg.append("g")     .attr("id", "textcontainer");  textcontainer.append("text")     .attr("x", xcoordinate)     .attr("y", ycoordinate)     .attr("text-anchor", "middle")     .text(text);  let bbox = (textcontainer.node() any).getbbox(); textcontainer.insert("rect", "#textcontainer text")     .attr("width", bbox.width)     .attr("height", bbox.height)     .attr("x", bbox.x)     .attr("y", bbox.y)     .attr("fill", "gray"); 

why issue happening?

the problem seems calculation of x , y positions rectangle. slight miscalculation when relative text inside view-box.

however, can resolve issue moving x , y position attributes container group element shown below.

let textcontainer = d3.select("svg").append("g").attr("id", "textcontainer");    textcontainer.attr("transform","translate(1,1)"); //apply position coordinates here     textcontainer.append("text")    .attr("x",0) //sets 0    .attr("y",0) //sets 0    .attr("text-anchor", "middle")    .attr("font-size", 0.5)    .text("test");    let bbox = textcontainer.node().getbbox();  textcontainer.insert("rect", "#textcontainer text")    .attr("width", bbox.width)    .attr("height", bbox.height)    .attr("x", bbox.x)    .attr("y", bbox.y)    .attr("fill", "gray");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>  <svg width="600" height="600" style="border: 1px solid black" viewbox="0 0 2 2">  </svg>

still, not perfect solution.


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -