【问题标题】:How to properly encode content of img src data:image/svg+xml?如何正确编码 img src data:image/svg+xml 的内容?
【发布时间】:2021-05-27 06:13:01
【问题描述】:

假设我们有一个像这样的简单 SVG:

<svg xmlns="http://www.w3.org/2000/svg" width="120" height="25">
    <rect x="0" y="0" width="120" height="25" stroke-wdith="1px" stroke="#000000" fill="#ffffff"/>
    <text x="60" y="15" stroke-width="0pt" font-family="arial,helvetica,sans-serif" font-size="11px" font-weight="normal" font-style="normal" text-decoration="none" display="inherit" text-anchor="middle">
        Some text & Other&nbsp;text
    </text>
</svg>

注意“&”字符和“nbsp”HTML 实体。

这会产生这个图像:

现在,如果我使用 encodeURIComponent 来获取图像的正确数据,我会得到:

%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120%22%20height%3D%2225%22%3E%3Crect%20x%3D%220%22%20y%3D%220%22%20width%3D%22120%22%20height%3D%2225%22%20stroke-wdith%3D%221px%22%20stroke%3D%22%23000000%22%20fill%3D%22%23ffffff%22%2F%3E%3Ctext%20x%3D%2260%22%20y%3D%2215%22%20stroke-width%3D%220pt%22%20font-family%3D%22arial%2Chelvetica%2Csans-serif%22%20font-size%3D%2211px%22%20font-weight%3D%22normal%22%20font-style%3D%22normal%22%20text-decoration%3D%22none%22%20display%3D%22inherit%22%20text-anchor%3D%22middle%22%3ESome%20text%20%26%20Other%26nbsp%3Btext%3C%2Ftext%3E%3C%2Fsvg%3E

在 HTML 图像中使用这个 图像不会加载。

要修复“nbsp”部分,我可以使用像 he 这样的库来解码 HTML。如果我删除“&”,它会起作用。

但是 '&',即使我看到它是用 %26 编码的,也会阻止图像加载。

我不知道是否还有其他类似的字符会阻止图像加载,所以我想知道我应该如何处理文本(可以是任何东西)以确保它始终正确呈现。

【问题讨论】:

  • “如果我使用 encodeURIComponent”部分在哪里?我们所说的“我的图像的正确数据”是什么数据?另外 svg 不是 img ,所以请添加更多解释,说明您甚至想要实现的目标。

标签: javascript svg


【解决方案1】:

它不是有效的 XML。您应该首先将&amp;amp; 替换为&amp;amp;。只有 5 个 XML 实体(&amp;lt;&amp;gt;&amp;amp;&amp;quot;&amp;apos;)。其他 HTML 实体根本不是 SVG 的一部分。您可以将 &amp;nbsp; 替换为 unicode \u00A0&amp;#160; 或真正的 unicode 字符“ ”。

最终&lt;text&gt;的内容可以是其中之一

Some text &amp; Other\u00A0text
Some text &amp; Other&#160;text
Some text &amp; Other text

【讨论】:

  • 看起来浏览器让我们在使用纯 SVG 表单时会出现这些错误,但在将其放入数据时不会!谢谢,这解决了我的问题。
  • @Melanie Firefox 如果您尝试使用其中一种 XML mime 类型以“纯格式”显示文件,那么肯定会给您一个错误。
【解决方案2】:

<img id=replaced>
<script>
  let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="300" height="150">
    <rect width="100%" height="100%" stroke="#000" fill="#0f0"/>
    <text x="50%" y="50%" font-size="25px" text-anchor="middle">
        Some text & Other text
    </text>
</svg>`;
  let replacedSVG = svg.replace(/#/g, '%23')
                       .replace(/"/g, "'")
                       .replace(/&/g, '&amp;');
  replaced.src = "data:image/svg+xml," + replacedSVG;
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 2020-12-14
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    相关资源
    最近更新 更多