2013-12-21 67 views
0

将图像设置为动态svg圆形的背景不起作用。我通过将图像的url设置为SVG圆形的填充属性来完成它,如下所示。用图像填充SVG圆形不起作用

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

这里是fiddle

有什么方法可以填充图像?

+0

可能重复(HTTP:/ /stackoverflow.com/questions/3796025/fill-svg-path-element-with-a-background-image) –

回答

1

我固定您fiddle

我取代不必要setAttributeNS呼叫与setAttribute并加入重要setAttributeNS呼叫:的[填充SVG路径元件与背景图像]

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); 
+0

非常感谢您的答案。它如何精确地将图像对齐到中心位置,尽管x和y值为0在我的示例中,为了在圆的中心对齐图像,我需要改变e x和y值。 –

+0

忘记提及我已将“height”和“width”图像属性的值更改为100。 – Tony