gpt4 book ai didi

javascript - 在圆圈内环绕文字

转载 作者:可可西里 更新时间:2023-11-01 02:05:29 25 4
gpt4 key购买 nike

我正在使用 d3 绘制 UML 图,并希望将文本包裹在使用 d3 绘制的形状中。我已经了解了下面的代码,但找不到使文本“适合”我的形状的解决方案(见下图)。

var svg =  d3.select('#svg')
.append('svg')
.attr('width', 500)
.attr('height', 200);

var global = svg.append('g');

global.append('circle')
.attr('cx', 150)
.attr('cy', 100)
.attr('r', 50);

global.append('text')
.attr('x', 150)
.attr('y', 100)
.attr('height', 'auto')
.attr('text-anchor', 'middle')
.text('Text meant to fit within circle')
.attr('fill', 'red');

result

最佳答案

这是我能做的最好的。

enter image description here

我想在 SVG 中将文本居中包裹在圆圈或矩形内。无论文本长度如何,文本都应保持居中(水平/垂直)。

svg {
width: 600px;
height: 200px;
background-color: yellow;
}
.circle {
background-color: blue;
height: 100%;
border-radius: 100%;
text-align: center;
line-height: 200px;
font-size: 30px;
}
.circle span {
line-height: normal;
display:inline-block;
vertical-align: middle;
color: white;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
}
<svg>
<foreignObject width="200" height="200" x="100" y="100" transform="translate(-100,-100)">
<div class="circle">
<span>Here is a</span>
</div>
</foreignObject>

<foreignObject width="200" height="200" x="300" y="100" transform="translate(-100,-100)">
<div class="circle">
<span>Here is a paragraph</span>
</div>
</foreignObject>

<foreignObject width="200" height="200" x="500" y="100" transform="translate(-100,-100)">
<div class="circle">
<span>Here is a paragraph that requires word wrap</span>
</div>
</foreignObject>
</svg>

transform 属性不是强制性的,我使用的是 translate(-r, -r),这样 foreignObject 的 (x,y) 就像 SVG 圆的 (cx, cy),宽度,高度 = 2*r,r 为半径。

我这样做是为了用作 D3 强制布局中的节点。我把这个片段翻译成 javascript D3 的风格作为练习。

关于javascript - 在圆圈内环绕文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20913869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com