Tim
Tim

Reputation: 2163

Dynamically loaded <image> not rendering in SVG

I'm trying to build the following SVG:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="render" height="200px" width="100%" viewBox="0 0 100 50">
  <image x="0" y="-25" width="100" height="50" xlink:href="https://environmentaldashboard.org/cv_slides/categorybars/nature_photos.png"></image>
</svg>

When the <image> is statically a part of the SVG, it loads fine. However, loading the image dynamically with JavaScript does not work:

var image = makeSVG('image', {
  x: 0,
  y: -25,
  width: 100,
  height: 50,
  'xlink:href': 'https://environmentaldashboard.org/cv_slides/categorybars/nature_photos.png'
});
document.getElementById('render').appendChild(image);
var circle = makeSVG('circle', {
  cx: 100,
  cy: 50,
  r: 40,
  stroke: 'black',
  'stroke-width': 2,
  fill: 'red'
});
document.getElementById('render').appendChild(circle);

function makeSVG(tag, attrs) { // https://stackoverflow.com/a/3642265/2624391
  var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
  for (var k in attrs) {
    el.setAttribute(k, attrs[k]);
  }
  return el;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="render" height="200px" width="100%" viewBox="0 0 100 50"></svg>

To be sure the makeSVG() function is working I'm also appending a <circle> which is rendering correctly. Why can I not load the <image> the same way? When I inspect element in my browser I can see the element highlighted, however, it is blank.

Upvotes: 0

Views: 224

Answers (1)

Alex S.
Alex S.

Reputation: 632

Use setAttributeNS method to add namespace related attribute xlink

for (var k in attrs) {
    if (k == 'xlink:href') {
        el.setAttributeNS("http://www.w3.org/1999/xlink", 'xlink:href', attrs[k]);
    } else {
        el.setAttribute(k, attrs[k]);
    }
}

Upvotes: 1

Related Questions