cel*_*822 11 html javascript svg
我有一条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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
579 次 |
最近记录: |