将 svg 图像的 base 64 定义移动到外部文件中

Move base 64 definition of svg image into an external file

我在 HTML 文件中有一个 SVG,它有一个以 base 64 编码的图像。而不是在 html 文件中有完整的 base 64 字符串,有没有一个好的方法将其保存在我在 <svg>?

中的 <image> 定义中引用的不同文件中

这里是有问题的代码片段:

<svg>
  <image
    y="0"
    x="0"
    id="image3698"
    xlink:href="data:image/jpeg;base64,/9j/4AAQSkL... [...thousands of  characters...]"
    height="1082.88"
    width="1280"/>
</svg>

我已经研究过为此使用 <use> 对象,但它似乎对这项任务来说太过分了(而且我无法使其正常运行)。

编辑:为了阐明我想要实现的目标(我不确定这是否可能)我想保留上面的代码结构,只用任何检索 a 的代码替换 xlink:href=... 行来自单独文件的字符串。我想这可以用 javascript 来完成,但我不知道怎么做。

这里是关于如何使用存储在单独文件中的 base64 数据在运行时更新 base64 属性的基本思路。在这种情况下,它在 Javascript 对象中被存储。

请注意,由于伪造的 base64 数据,此示例无法运行。

base64imgData = {
  'foo': "data:image/jpeg;base64,/9j/4AAQSkL... [...thousands of  characters...]"
}

// Get a reference to our <image> element
var img = document.getElementById("image3698");

// Update the xlink:href attribute on the element
// Needs to be done a special way because of the attribute's namespace ("xlink:")
xlinkNS = "http://www.w3.org/1999/xlink";
img.setAttributeNS(xlinkNS, "xlink:href", base64imgData.foo);
<svg>
  <image
    y="0"
    x="0"
    id="image3698"
    xlink:href=""
    height="1082.88"
    width="1280"/>
</svg>