我在 HTML 文件中有一个 SVG,其中有一个以 Base 64 编码的图像。有没有一种好方法可以将其保存在我引用的不同文件中,而不是在 html 文件中包含完整的 Base 64 字符串在我的<image>
<svg>
中的定义?
这里是相关代码的片段:
<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>
对象为此,但对于这项任务来说似乎有点矫枉过正(而且我无法让它正常运行)。
编辑:为了澄清我想要实现的目标(并且我不确定这是否可能),我想保留上面的代码结构,仅替换 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>
关于javascript - 将 svg 图像的 Base 64 定义移动到外部文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42094591/