html - 如何使 svg 大小适合内容文本
问题描述
请检查我的代码链接
<div class="suj_content">
<header class="suj_content_hd">
<div id="suj_content_hd_ytb"><iframe class="suj_content_hd_ytb" src="https://www.youtube.com/embed/kOc6ME2J_Us?mute=1&loop=1&playlist=kOc6ME2J_Us&autoplay=1&showinfo=0&controls=0" width="100%" height="100%" frameborder="0"></iframe></div>
<h2>
<svg id="suj_content_svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100% 100%" preserveAspectRatio="xMidYMid slice">
<defs>
<mask id="mask" x="0" y="0" width="100%" height="100%">
<rect x="0" y="0" width="100%" height="100%"></rect>
<text>
<tspan x="0" dy="33.333333333333%" alignment-baseline="middle" text-anchor="start">mittel</tspan><tspan x="0" dy="23.222222222222%" alignment-baseline="middle" text-anchor="start">stand</tspan><tspan x="0" dy="23.222222222222%" alignment-baseline="middle" text-anchor="start">digital</tspan> </text>
</mask>
</defs>
<rect x="0" y="0" width="100%" height="100%"></rect>
</svg>
</h2>
</header>
如何设置 SVG 标签的宽度和高度以适合其内容(tspan 标签)。tspan 标签的数量不固定。
谢谢
解决方案
首先:您使用了无效的 viewBox 属性。不允许使用百分比。viewBox 的值为fromX fromY width height
。
我正在使用宽度为 41 的 viewBox - 文本边界框的宽度。
第二:我怀疑您打算从最后一个矩形中删除文本。在这种情况下,您需要将文本设为白色。
console.log(t.getBBox())
text{font-size:16px;}
<svg id="suj_content_svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 41 50" preserveAspectRatio="xMidYMid slice">
<defs>
<mask id="mask" x="0" y="0" width="100%" height="100%">
<rect x="0" y="0" width="100%" height="100%"></rect>
<text fill="white" id="t">
<tspan x="0" dy="25%" dominant-baseline="middle" text-anchor="start">mittel</tspan>
<tspan x="0" dy="25%" dominant-baseline="middle" text-anchor="start">stand</tspan>
<tspan x="0" dy="25%" dominant-baseline="middle" text-anchor="start">digital</tspan>
</text>
</mask>
</defs>
<rect x="0" y="0" width="100%" height="100%" mask="url(#mask)"></rect>
</svg>
推荐阅读
- sparql - SPARQL:从可能的关系列表中查找连接两个实体的关系
- java - 带有 GraphQL 服务器的 Spring Boot 未启动
- python - 是否可以将变量或对象的属性传递给函数或方法?
- python - 在文本文件中的特定位置插入数据,Python
- python - 使用标签在数据透视表中绘图
- jdbc - 如何从 HAProxy 中的 TCP 连接中拦截 jdbc 连接字符串
- javascript - 用于 2D 上下文绘图的 chrome 中的慢速复合层
- java - 如何正确设置监听器?
- html - 如何在 HTML 的这个位置对齐这两个元素?
- c# - NHibernate:如何转换列表