简体   繁体   中英

How to add an image to a svg element in javascript?

I am building a svg element in pure Javascript, but I don't manage to add images to it :

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

You need this to set the href attribute, although why you're calling the variable pngImage when it sets a svg image is beyond me.

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

You're also confused about whether the variable is pngImage or pgnImage, a browser debugger will inform you of that problem.

Like so

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM