0

Hi I am trying to add a background image on svg rectangle. But unfortunately I am not able to see the image in the rectangle's background. My code snippet is

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");

I also able to see my code in as html in chrome debugger as

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

But no background image is seen. Image location is proper. Any help would be appreciated. Thanks

sakthisundar
  • 3,278
  • 3
  • 16
  • 29

1 Answers1

1

The <defs> element only defines this pattern, it doesn't actually cause it to be rendered anywhere. Artifacts defined in a defs need to be referenced by other visible elements.

In order to reference a definition you need to give it a unique id. (Note that the defs can live anywhere in the SVG and can be referenced by any other element or elements).

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

Then, you need to set the fill attribute of your rect to reference your defined pattern:

rectCanvas_o = parentElement.append("rect")
    .attr("width", "30")
    .attr("height","100%").
    .attr("class", this.currentAlarmClass_s)
    .style("fill", "url(#my_pattern)");
Scott Cameron
  • 5,293
  • 2
  • 29
  • 32
  • 1
    Oh, I just noticed that your defs is inside your rect. Try to move it out so that the entire defs element lives at the same level as the rect element. – Scott Cameron Mar 18 '14 at 16:44
  • Hi Scott, I did that, but it didn't work either. I don't know if I am doing anything unusually silly – sakthisundar Mar 19 '14 at 05:05
  • Here's a similar post that might help for comparison. http://stackoverflow.com/questions/3796025/fill-svg-path-element-with-a-background-image. Also, can you update your question with the final DOM snippet so we can see it all together? – Scott Cameron Mar 19 '14 at 15:31
  • Scott, Thanks first of all. It worked when I used id for pattern. – sakthisundar Mar 20 '14 at 09:39
  • Glad you figured it out. I've updated the answer based on your suggested edit. Thanks! – Scott Cameron Mar 20 '14 at 15:37