0

Setting image as background for svg circle dynamically is not working.I have done it by setting url of the image to the fill attribute of SVG circle as below.

  document.getElementsByTagName('circle')[0].setAttribute("fill", "url(#img1)");

Here is the fiddle.

Is there any way to fill image??

Swarna Latha
  • 1,004
  • 12
  • 21
  • possible duplicate of [Fill SVG path element with a background-image](http://stackoverflow.com/questions/3796025/fill-svg-path-element-with-a-background-image) – Robert Longson Dec 21 '13 at 07:12

1 Answers1

1

I fixed your fiddle:

I replaced unnecessary setAttributeNS calls with setAttribute and added important setAttributeNS call:

var circle = $('circle');

var pattern = document.createElementNS("http://www.w3.org/2000/svg", "pattern");
pattern.setAttribute( "id", "img1");
pattern.setAttribute( "patternUnits", "userSpaceOnUse");
pattern.setAttribute("height", "100");
pattern.setAttribute("width", "100");
var image = document.createElementNS("http://www.w3.org/2000/svg", "image");
image.setAttribute("x", "0");
image.setAttribute("y", "0");
image.setAttribute("height", "100");
image.setAttribute("width", "100");
image.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", 
                     "http://www.abcteach.com/free/c/circlergb.jpg");

pattern.appendChild(image);
defs.appendChild(pattern);
$(defs).insertBefore(circle);
Tony
  • 7,345
  • 3
  • 26
  • 34
  • Thanks a lot for your answer.How does it align an image exactly in center position though x and y values are 0??.In my sample to align image in the center of circle I need to change x and y value. – Swarna Latha Dec 21 '13 at 10:13
  • Forget to mention that I have changed value of `height` and `width` image attributes to 100. – Tony Dec 21 '13 at 13:44