Reputation: 21
How can I make the bounding box of an element as tight as possible? I’m working with SVG, and when I add a text
element, the bounding box shows a lot of whitespace. The tspan
element itself has a tight bounding box horizontally, but there’s also whitespace on top. The parent text element has a lot of whitespaces.
Bounding boxes are crucial for my project. Is there a fix for this? Thank you!
Element with bbox:
Tried manually computing the text width and height but I guess im doing it wrong too.
My current code is just a simple JS element create/append like this.
// Create a text element
const textElement = document.createElementNS("http://www.w3.org/2000/svg", "text");
textElement.setAttribute("x", "10");
textElement.setAttribute("y", "50");
textElement.setAttribute("font-family", "Arial");
textElement.setAttribute("font-size", "24");
textElement.setAttribute("fill", "black");
// Create tspan elements
const tspan1 = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
tspan1.textContent = "Hello, ";
tspan1.setAttribute("fill", "blue"); // Change color for the first tspan
const tspan2 = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
tspan2.textContent = "World!";
tspan2.setAttribute("fill", "green"); // Change color for the second tspan
// Append tspan elements to the text element
textElement.appendChild(tspan1);
textElement.appendChild(tspan2);
// Append the text element to the SVG container
const svgContainer = document.getElementById("svgContainer");
svgContainer.appendChild(textElement);
The html element
<text text-rendering="geometricPrecision" sketch="true" font-family="Arial" font-size="1.8" x="111.1137386440559" y="54.55384757729337" transform="rotate(0,0,0)" text-anchor="start"><tspan dx="0" x="111.1137386440559" dominant-baseline="middle">Bracket</tspan></text>
Upvotes: 0
Views: 38