html5 – 如何限制或剪辑SVG中的文本?

前端之家收集整理的这篇文章主要介绍了html5 – 如何限制或剪辑SVG中的文本?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在SVG中做了一个表,我想动态地填充数据。这意味着我不知道文本占用了多少空间,我想剪辑或隐藏重叠文本。如何在SVG中这样做?

我的HTML文档与SVG看起来像:

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <svg>
  5. <text x="100" y="100">Orange</text> <text x="160" y="100">12</text>
  6. <text x="100" y="115">Pear</text> <text x="160" y="115">7</text>
  7. <text x="100" y="130">Banana</text> <text x="160" y="130">9</text>
  8. <text x="100" y="145">Pomegranate</text><text x="160" y="145">2</text>
  9.  
  10. <line x1="157" y1="85" x2="157" y2="155" style="stroke:rgb(100,100,100)"/>
  11. </svg>
  12. </body>
  13. </html>

这将呈现:

有什么办法可以剪辑文本我的SVG-“表”?

Erik答案的解决方

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <svg>
  5. <text x="10" y="20" clip-path="url(#clip1)">Orange</text>
  6. <text x="10" y="35" clip-path="url(#clip1)">Pear</text>
  7. <text x="10" y="50" clip-path="url(#clip1)">Banana</text>
  8. <text x="10" y="65" clip-path="url(#clip1)">Pomegranate</text>
  9.  
  10. <text x="70" y="20">12</text>
  11. <text x="70" y="35">7</text>
  12. <text x="70" y="50">9</text>
  13. <text x="70" y="65">2</text>
  14.  
  15. <line x1="67" y1="5" x2="67" y2="75" style="stroke:rgb(100,100)"/>
  16.  
  17. <clipPath id="clip1">
  18. <rect x="5" y="5" width="57" height="90"/>
  19. </clipPath>
  20. </svg>
  21. </body>
  22. </html>

解决方法

您可以使用 clip-path剪辑任何想要的形状,从svg testsuite中看到例如 masking-path-01

相关部分,定义剪辑路径:

  1. <clipPath id="clip1">
  2. <rect x="200" y="10" width="60" height="100"/>
  3. ... you can have any shapes you want here ...
  4. </clipPath>

然后应用剪辑路径,如下所示:

  1. <g clip-path="url(#clip1)">
  2. ... your text elements here ...
  3. </g>

猜你在找的HTML5相关文章