I have an SVG path that draws the outline of a jersey, and I want to center players' last names within that jersey. Also, since I'll be putting names of varying length into the jersey, I wanted to make the size of the text dynamically scale to fit the jersey.
I was able to center the text with some math involving getBoundingClientRect(), but I'm struggling with the dynamic sizing of the text. It looks fine at first, but then when I resize the screen, the text size does not remain proportional to the size of jersey.
I've included a code snippet below to demonstrate. Please help me understand why this sizing issue is occurring, and what I can do to achieve the proper text resizing.
EDIT: I now have enough reputation points to add images (woo!), so here are some pictures to demonstrate the resizing problem I'm referring to. The text does not scale proportionally with the jersey size when I zoom in/out. BUT, if I refresh the page after I zoom in/out, i.e. so that I start out with the zoomed-in/out version, the text size readjusts to the current jersey size and fits the jersey as desired.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Jersey</title>
</head>
<body>
<svg id="jersey">
<switch>
<g>
<g id="jerseyShape">
<path id="outline" fill="green" transform="translate(-40,0)" opacity="0.35" fill="none" stroke="#000000" stroke-width="1.5" d="M116.462,113.911V39.01
c0,0-18.493-5.977-15.317-30.633c0,0-8.033-2.616-8.78-3.363S91.617,9.311,79.29,9.124h-1.305
C65.656,9.311,65.656,4.268,64.909,5.015s-8.778,3.363-8.778,3.363C59.305,33.034,40.813,39.01,40.813,39.01v74.901
C40.813,113.911,74.434,126.427,116.462,113.911z" />
</g>
<g id="jerseyContent">
<svg>
<text id="name" font-family="Verdana" text-anchor="middle" dominant-baseline="central">
Jordan
</text>
<!-- Dynamically re-size name to fit jersey -->
<script type="application/ecmascript">
//Get path's bounding rectangle
var pathNode = document.getElementById("outline");
var pRect = pathNode.getBoundingClientRect();
//Get text's bounding rectangle
var textNode = document.getElementById("name");
var tRect = textNode.getBBox();
//Calculate the necessary scale to make the text fit within the jersey width while
//not exceeding a height of 30
var widthRatio = (pRect.width * 0.85) / tRect.width;
var heightRatio = (pRect.height*0.3) / tRect.height;
var textScale = Math.min(widthRatio, heightRatio);
//Translate text to center of jersey and scale to fit
textNode.setAttribute("transform", "translate(" + (1 + pRect.width / 2) + " " + (pRect.top + pRect.height / 2) + ")scale(" + textScale + ")");
</script>
</svg>
</g>
</g>
</switch>
</svg>
</body>
</html>
You should also use getBBox()
fo get the size of the path as well. That way, the dimensions will be in the same coordinate space even after scaling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With