我想在 inside SVG rect
中显示一些文本。可能吗?
我试过了
<svg xmlns="http://www.w3.org/2000/svg">
<g>
<rect x="0" y="0" width="100" height="100" fill="red">
<text x="0" y="10" font-family="Verdana" font-size="55" fill="blue"> Hello </text>
</rect>
</g>
</svg>
但它不起作用。
这是不可能的。如果要在 rect 元素内显示文本,则应将它们放在一个组中,文本元素位于 rect 元素之后(因此它显示在顶部)。
以编程方式使用 D3:
body = d3.select('body')
svg = body.append('svg').attr('height', 600).attr('width', 200)
rect = svg.append('rect').transition().duration(500).attr('width', 150)
.attr('height', 100)
.attr('x', 40)
.attr('y', 100)
.style('fill', 'white')
.attr('stroke', 'black')
text = svg.append('text').text('This is some information about whatever')
.attr('x', 50)
.attr('y', 150)
.attr('fill', 'black')
<svg><rect/><text/></svg>
。
您可以使用 foreignobject 进行更多控制并将丰富的 HTML 内容放置在矩形或圆形上
https://i.stack.imgur.com/yr8pb.png
text
-tags-only 选项不同,此选项实际上将文本放置在路径内,而不是将其隐藏在其上方的某个不可见空间中! x
和 y
属性对我来说不是必需的,但 width
和 height
是必需的,或者它也无处可见!
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<g>
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(145,200,103);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(132,168,86);stop-opacity:1" />
</linearGradient>
</defs>
<rect width="220" height="30" class="GradientBorder" fill="url(#grad1)" />
<text x="60" y="20" font-family="Calibri" font-size="20" fill="white" >My Code , Your Achivement....... </text>
</g>
</svg>
使用基本 Javascript 以编程方式在矩形上显示文本
var svg = document.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0]; var text = document.createElementNS('http://www.w3.org/2000/svg', 'text'); text.setAttribute('x', 20); text.setAttribute('y', 50); text.setAttribute('宽度', 500); text.style.fill = '红色'; text.style.fontFamily = 'Verdana'; text.style.fontSize = '35'; text.innerHTML = "一些文本行"; svg.appendChild(文本); var text2 = document.createElementNS('http://www.w3.org/2000/svg', 'text'); text2.setAttribute('x', 20); text2.setAttribute('y', 100); text2.setAttribute('宽度', 500); text2.style.fill = '绿色'; text2.style.fontFamily = 'Calibri'; text2.style.fontSize = '35'; text2.style.fontStyle = '斜体'; text2.innerHTML = "一些斜体线"; svg.appendChild(text2); var text3 = document.createElementNS('http://www.w3.org/2000/svg', 'text'); text3.setAttribute('x', 20); text3.setAttribute('y', 150); text3.setAttribute('宽度', 500); text3.style.fill = '绿色'; text3.style.fontFamily = 'Calibri'; text3.style.fontSize = '35'; text3.style.fontWeight = 700; text3.innerHTML = "一些粗线"; svg.appendChild(text3);
https://i.stack.imgur.com/GMT2u.png
不定期副业成功案例分享
g
元素在这里有一个隐式大小,我希望矩形扩展到它的大小。