我有一个绘制运动衫轮廓的SVG路径,并希望将球员的姓氏居中在衣服内。此外,由于我将各种长度的名称放入球衣中,我希望文本大小能够动态缩放以适合球衣。
我使用getBoundingClientRect()进行了一些数学计算来居中文本,但我正在解决文本的动态大小调整问题。起初看起来还好,但当我调整窗口大小时,文本大小并不与球衣大小成比例。
我在下面包含了一段代码片段以演示。请帮助我理解为什么会出现这种大小调整问题,以及我可以做些什么来实现正确的文本调整大小。
编辑:我现在拥有足够的声望点来添加图片(万岁!),因此以下是一些图片,用于演示我所指的调整大小问题。当我放大/缩小时,文本大小不会与球衣大小成比例。但是,如果我在放大/缩小后刷新页面,即以缩放版本开始,文本大小将重新调整为当前运动衫大小并适合运动衫。
<!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>