无法在svg rect中看到背景图像

时间:2014-03-18 15:07:23

标签: javascript html svg d3.js

您好我正在尝试在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");

我还可以在chrome调试器中将我的代码视为html

<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>

但没有看到背景图片。图像位置是正确的。任何帮助,将不胜感激。感谢

1 个答案:

答案 0 :(得分:1)

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

为了引用定义,您需要为其提供唯一ID。 (请注意,defs可以存在于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)");
相关问题