使用`<use>`元素为SVG生成IMG src数据URI 注意:

问题描述

是否有安全原因阻止<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都会给出如下错误消息:

enter image description here

enter image description here

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

<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中转义>

也不需要过时的xlink表示法。

但是 必须%23

转义

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

这将生成正确的字符串

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

注意:

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...