我已将 base64编码的图片加载到'xlink:href'
图片标记的#patternImage
属性中。在 Chrome 和 Firefox 中可以正常工作,但在 Safari 中则不能工作。
HTML:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id='svgId' width="576" height="720" style="outline:auto;" >
<defs>
<pattern id="imgpattern" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
<image id="patternImage" xlink:href="" width="20" height="20"></image>
</pattern>
</defs>
<path id="svgpath" stroke="#f000" fill="#ff0000" stroke-width="0.25px" style="fill:url(#imgpattern) !important"></path>
</svg>
JS:
$("#patternImage").attr("xlink:href",encodedImage);
$("#patternImage").load(function(){
console.log("Loaded");
});
答案 0 :(得分:0)
谢谢Kaiido
解决方案是:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id='svgId' width="576" height="720" style="outline:auto;">
<defs>
<pattern id="imgpattern" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
<image id="patternImage" xlink:href="" width="20" height="20"></image>
</pattern>
</defs>
<path id="svgpath" stroke="#f000" fill="#ff0000" stroke-width="0.25px" style="fill:url(#imgpattern)" d="M0,0H576V720H0z"></path>
</svg>
JavaScript:
fetch("https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg").then(r => r.blob())
.then(b => new Promise(res => {
const f = new FileReader();
f.onload = e => res(f.result);
f.readAsDataURL(b);
}))
.then(encodedImage => {
$("#patternImage").attr("xlink:href", encodedImage);
$("#patternImage").load(function() {
});
});