math - 计算 SVG 甜甜圈切片标签位置服务器端
问题描述
如何计算切片文本标签以直接定位在 svg 圆环图中切片的中心?
我有一个在服务器端生成的 svg 甜甜圈图。我已经正确实现了图表的切片,但是我在计算将每个单独的切片标签放置在其各自切片的中心内时遇到了一些麻烦。标签将是它占据的切片的百分比。
这是 svg 的精简版。
<svg width="100%" height="100%" viewBox="0 0 42 42">
<circle cx="21" cy="21" r="15.91549430918954" fill="transparent" stroke="#d2d3d4" stroke-width="3" />
<circle
cx="21"
cy="21"
r="15.91549430918954"
fill="transparent"
stroke="#b1c94e"
stroke-width="3"
stroke-dasharray="25 75"
stroke-dashoffset="25"
/>
<!-- How do I calculate x and y so the text is in the center of the above slice. -->
<text x="80%" y="30%" font-size="6" text-anchor="middle">25%</text>
</svg>
这是 svg 的 jsfiddle。https://jsfiddle.net/xgyzvnka/
解决方案
我就是这样做的。请更改 的值perc
。请阅读我的代码中的注释。
let r = 16;//circles radius
let perc = .15//percentage
//the angle used to draw the circle
let angle = 2*Math.PI * perc;
// the circle's circumference
let totalLength = base.getTotalLength();
//the length of the dash
let length_perc = totalLength * perc;
//the length of the gap
let difference = totalLength * (1 - perc);
test.setAttributeNS(null,"stroke-dasharray",length_perc+", "+difference);
//rotate backwards 90degs. The center of rotation is the center of the circle; 21,21
test.setAttributeNS(null,"transform","rotate(-90,21,21)");
//the point where to draw the circle
let textPoint = {x:21 + r * Math.cos((angle - Math.PI)/2),
y:21 + r * Math.sin((angle - Math.PI)/2)}
text.setAttributeNS(null,"x",textPoint.x);
text.setAttributeNS(null,"y",textPoint.y);
//the text
text.textContent = perc * 100 + "%";
text{text-anchor:middle; dominant-baseline:middle;}
svg{width:90vh;}
<svg viewBox="0 0 42 42">
<circle id="base" cx="21" cy="21" r="16" fill="transparent" stroke="#d2d3d4" stroke-width="3" />
<circle id="test"
cx="21"
cy="21"
r="16"
fill="transparent"
stroke="#b1c94e"
stroke-width="3"
/>
<text id="text" font-size="6" text-anchor="middle"> </text>
</svg>
推荐阅读
- python - BeautifulSoup 和 CSV:每个字符后的分隔符
- python - 以特殊字符为标记搜索多个子字符串
- jspdf - 有没有办法在一个单元格中为每个单词设置自己的颜色?
- c# - 如何将 SQL 查询结果转换为 Lambda 表达式
- python - 我是否正在处理一个忽略 CancelledError 的异步任务?
- shell - 查找文件中定义的条目的中位数
- c# - 是否可以在 C# .Net 应用程序和 Laravel 5 应用程序之间实现单点登录 SSO?
- python - Python3 中的列表索引是如何工作的?
- javascript - 从 onclick 方法调用 href 不起作用
- javascript - 如何使用 jquery 和 ajax 将 html 数据替换为 json 数组