1

I have a web application using SVG for a drawing canvas. Drawing scribbles and writing text works. Now I want to be able to add bitmap images to the canvas. This does not work at all.

I am trying to add an image to the SVG via the <image> tag. If I write static HTML that works like you would expect. However, I am creating only the SVG document in HTML code, all other elements are created dynamically via JavaScript. While this works for paths and text elements, it does not seem to work for images. I would like to know, why.

I created a JSFiddle to demonstrate the problem: http://jsfiddle.net/cc4PH/1/. As you can see in the developer tools, the code is the same in the static case and the dynamic case. But only in the static case the image is displayed. This is no browser-specific problem. I could reproduce it with Chrome, Firefox, Safari and Opera.

Do I have to somehow tell SVG to load the image?

Thanks in advance!

j0ker
  • 4,069
  • 4
  • 43
  • 65
  • possible duplicate of [Programmatically creating an SVG image element with javascript](http://stackoverflow.com/questions/6701705/programmatically-creating-an-svg-image-element-with-javascript) – fatsmcgee Jul 26 '13 at 18:10

1 Answers1

1

Looks like the issue is with the xlink:href attribute. Seems that setAttributeNS() needs to be used for that one, as a dynamically-created image doesn't know to get the reference to the xlink namespace from the svg element. The fix is as follows:

var $img = $(document.createElementNS('http://www.w3.org/2000/svg', 'image')).attr({width: 200, height: 200});
$img.get(0).setAttributeNS('http://www.w3.org/1999/xlink', 'href', url);

http://jsfiddle.net/cc4PH/6/

Interestingly, that also means that the xmlns:xlink attribute is not needed in the creation of the svg element if the linked images will only be added dynamically, as shown here: http://jsfiddle.net/cc4PH/8/

JAB
  • 20,783
  • 6
  • 71
  • 80
  • Yes, you don't need the `xmlns:xlink` attribute on the root if you just want to display the svg. However, if you want to serialize the svg (for copy-paste or external editing) you will most likely want it there (and the corresponding `xlink:` prefix on the `href` attributes) as well. – Erik Dahlström Aug 22 '13 at 08:34