无法在svg矩形中看到背景图像

Not able to see the background image in svg rect

本文关键字:背景 图像 svg      更新时间:2023-09-26

嗨,我正在尝试添加svg矩形的背景图像。但不幸的是,我无法看到矩形背景中的图像。我的代码片段是

rectCanvas_o = parentElement.append("rect");
rectCanvas_o.attr("width", "30").attr("height","100%").
attr("class", this.currentAlarmClass_s);

rectCanvas_o.append("defs").append("pattern").
attr("width", 20).attr("height", 20).
attr('patternUnits', 'userSpaceOnUse').append("image").
attr("width", 20).attr("height", 20).
attr("xlink:href", "image.png");

我也可以看到我的代码作为html在chrome调试器

<rect width="30" height="100%" class="eq__NEcontainer__currentAlarmAction">
<defs>
  <pattern width="20" height="20" patternUnits="userSpaceOnUse">
   <image width="20" height="20" xlink:href="image.png"></image>
  </pattern>
</defs>
</rect>

但是没有看到背景图像。图像位置正确。任何帮助都会很感激。由于

<defs>元素只定义了这个模式,它实际上并没有导致它在任何地方呈现。在defs中定义的工件需要被其他可见元素引用。

为了引用一个定义,你需要给它一个唯一的id。(请注意,def可以位于SVG中的任何位置,并且可以由任何其他元素或元素引用)。

rectCanvas_o.append("defs").append("pattern").attr("id", "my_pattern");

然后,你需要设置rect的fill属性来引用你定义的模式:

rectCanvas_o = parentElement.append("rect")
    .attr("width", "30")
    .attr("height","100%").
    .attr("class", this.currentAlarmClass_s)
    .style("fill", "url(#my_pattern)");