0

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

loloof64
  • 5,252
  • 12
  • 41
  • 78
  • What are you trying to do? SVG are Scalable Vector Graphics... they are images, however they use coordinates instead of set pixels... Are you trying to draw your own points? Good luck! – Trevor Clarke Mar 26 '16 at 17:09
  • Create an image element inside of the svg. https://stackoverflow.com/questions/6249664/does-svg-support-embedding-of-bitmap-images#6250418 –  Mar 26 '16 at 17:11
  • Updtated the JSFiddle to use an svg instead of a png image. – loloof64 Mar 26 '16 at 17:13
  • @user104317 I want to do this in Javascript because the use case is in a angular directive creation. – loloof64 Mar 26 '16 at 17:13
  • Note that there is a typo in pgnImage instead of pngImage. – Neri Barakat Sep 09 '20 at 13:40

1 Answers1

2

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

Robert Longson
  • 118,664
  • 26
  • 252
  • 242