使用“”元素为 SVG 生成 IMG src 数据 URI

2024-04-25

是否存在安全原因阻止<use>数据 URI 图像中的元素?我尝试过这样的事情:

const svg = document.querySelector("svg");
const img = document.querySelector("img");
img.src = "data:image/svg+xml;charset=UTF-8," + encodeURI(svg.outerHTML);
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <rect id="foo" width="100" height="100"/>
  <use xlink:href="#foo" x="10" y="10"/>
</svg>
<img src=""/>

如果我直接访问数据 URI,Chrome 和 Firefox 都会给出如下错误消息:

损坏图像的示例<use>数据 URI 中的元素:

<img src="data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20xmlns:xlink=%22http://www.w3.org/1999/xlink%22%20width=%22110%22%20height=%22110%22%3E%0A%20%20%3Crect%20id=%22foo%22%20width=%22100%22%20height=%22100%22/%3E%0A%20%20%3Cuse%20xlink:href=%22#foo%22%20x=%2210%22%20y=%2210%22/%3E%0A%3C/svg%3E%0A"/>

在现代浏览器中你不必逃避< and >不再在 SVG 数据 URI 中。

也不是过时的xlink需要注释。

But # must被逃脱%23

对于字符串处理,使用单引号更容易

这使得正确的string:

data:image/svg+xml,
<svg xmlns='http://www.w3.org/2000/svg' 
     viewBox='0 0 96 96'>
<rect id='USED' width='50%' height='50%' stroke='red'/>
<use href='%23USED' x='24' y='24'/>
</svg>
<style>
 rect{
  fill:blue !important; /* would work for INline SVG, not for data URI SVG */
 }
 img {
   width:200px;
   filter: drop-shadow(5px 5px 5px gold);
 }
</style>
<img src="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 96 96'><rect id='USED' width='50%' height='50%' stroke='red'/><use href='%23USED' x='24' y='24'/></svg>">

Notes:

  • IMG src 将 SVG 放置在(内部)shadowRoot 中,因此您无法再应用 CSS

  • 图像仍然是 SVG,由 SVG 解析器处理,因此所有 SVG 都适用...是的,您可以添加 SMIL 动画

  • 这是摆脱(臃肿)IconFonts 的好方法
    https://www.lambdatest.com/blog/its-2019-lets-end-the-debate-on-icon-fonts-vs-svg-icons/ https://www.lambdatest.com/blog/its-2019-lets-end-the-debate-on-icon-fonts-vs-svg-icons/

  • 既然你标记了你的问题WebComponent, see: https://IconMeister.github.io https://IconMeister.github.io

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用“”元素为 SVG 生成 IMG src 数据 URI 的相关文章