使用 `<use>` 元素为 SVG 生成 IMG src 数据 URI [英] Generate IMG src data URI for SVG with `<use>` elements

查看:109
本文介绍了使用 `<use>` 元素为 SVG 生成 IMG src 数据 URI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Are there security reasons that prevent <use> elements from working in data URI images? I tried something like this:

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 都会给出这样的错误消息:

Both Chrome and Firefox give error messages like this if I access the data URI directly:

数据 URI 中带有 元素的损坏图像示例:

Example of broken image with <use> element in data 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"/>

推荐答案

在现代浏览器中,您不必在 SVG 数据 URI 中转义 <>不再.

In modern browsers you don't have to escape < and > in SVG data URI any longer.

也不需要过时的 xlink 符号.

Neither is the outdated xlink notation required.

但是# 必须%23

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

And for string handling it is easier to use single quotes

这就是正确的字符串:

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>">

  • IMG src 将 SVG 置于(内部)shadowRoot 中,因此您不能再应用 CSS

  • IMG src places the SVG in a (internal) shadowRoot, so you can't apply CSS anymore

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

The image remains an SVG, handled by the SVG parser, so all SVG applies... yes, you can add SMIL animations

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

It is a good way to get rid of (bloated) IconFonts
https://www.lambdatest.com/blog/its-2019-lets-end-the-debate-on-icon-fonts-vs-svg-icons/

并且由于您标记了您的问题 WebComponent,请参阅:https://IconMeister.github.io

and since you tagged your question WebComponent, see: https://IconMeister.github.io

这篇关于使用 `&lt;use&gt;` 元素为 SVG 生成 IMG src 数据 URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆