问题描述
我想将SVG用作HTML元素的background-image
。但是,当我在SVG中的任何位置使用遮罩时,此操作将失败。在下面的代码中删除mask="url(#m)"
时,SVG被显示为背景图像而没有问题。
HTML:
<div>Some element.</div>
JavaScript:
// The following SVG is correctly rendered as a standalone SVG file,but not in `background-image`.
const svg = `<svg viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
<mask id="m" maskContentUnits="objectBoundingBox">
<rect fill="white" x="0" y="0" width="100%" height="100%" />
</mask>
<rect mask="url(#m)" width="100" height="100" fill="red" />
</svg>`;
document.querySelector("div").style.backgroundImage = `url(data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;
是否可以像这样在background-image
中使用SVG掩码?如果没有,原因是什么?
相关地,如果我将style="transform: translate(0)"
添加到svg
,背景图像也将无法显示(尽管其他样式,例如style="background-color: blue"
可以正常工作)。可以在SVG transform
中使用background-image
吗?
解决方法
您的数据URL语法错误
document.querySelector("div").style.backgroundImage = `url('data:image/svg+xml,${encodeURIComponent(svg)}')`;
就是你想要的
const svg = `<svg viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
<mask id="m" maskContentUnits="objectBoundingBox">
<rect fill="white" x="0" y="0" width="100%" height="100%" />
</mask>
<rect mask="url(#m)" width="100" height="100" fill="red" />
</svg>`;
document.querySelector("div").style.backgroundImage = `url('data:image/svg+xml,${encodeURIComponent(svg)}')`;
<div>Some element.</div>