带有掩码的SVG作为HTML元素的背景图片

问题描述

我想将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)}`;

JSFiddle link

结果:

no background image

预期结果:

intended background image

是否可以像这样在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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...