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!

1

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.