如何在javascript中将图像添加到svg元素?

时间:2016-03-26 17:06:48

标签: javascript svg

我在纯Javascript中构建svg元素,但我无法向其添加图像:

var svgns = "http://www.w3.org/2000/svg";

var svgElement = document.createElementNS(svgns, "svg");
svgElement.setAttributeNS(null, "width", 100);
svgElement.setAttributeNS(null, "height", 100);

var shape = document.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r",  20);
shape.setAttributeNS(null, "fill", "green");

var pngImage = document.createElementNS(svgns, "image");
pgnImage.setAttributeNS(null, "x", 0);
pgnImage.setAttributeNS(null, "y", 0);
pgnImage.setAttributeNS(null, "width", 100);
pgnImage.setAttributeNS(null, "height", 100);
pngImage.setAttributeNS(null, "http://www.freedos.org/images/logos/fdfish-glossy-plain.svg")


svgElement.appendChild(shape);
svgElement.appendChild(pgnImage);

document.body.appendChild(svgElement);

Here is my JSFiddle

1 个答案:

答案 0 :(得分:1)

你需要这个来设置href属性,虽然你在设置svg图像时调用变量pngImage的原因超出了我的范围。

pngImage.setAttributeNS("http://www.w3.org/1999/xlink", "href", "http://www.freedos.org/images/logos/fdfish-glossy-plain.svg")

您还对变量是pngImage还是pgnImage感到困惑,浏览器调试器会告诉您该问题。

Like so