Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not add image inside SVG via jQuery: <image /> tag becomes <img />

Tags:

jquery

svg

I want to add items in an SVG via jQuery. I can well insert tags such as <rect /> or <text /> but I can not insert images with the tag <image />.

This tag becomes <img /> automatically, which can not display an image in SVG: http://jsfiddle.net/G4mJf/

How can I prevent this? If it is impossible, is there another way to insert images in SVG using JavaScript/jQuery.

like image 806
Pacien Avatar asked Apr 21 '12 18:04

Pacien


2 Answers

you should use createElementNS():

var img = document.createElementNS('http://www.w3.org/2000/svg','image');
img.setAttributeNS(null,'height','536');
img.setAttributeNS(null,'width','536');
img.setAttributeNS('http://www.w3.org/1999/xlink','href','https://upload.wikimedia.org/wikipedia/commons/2/22/SVG_Simple_Logo.svg');
img.setAttributeNS(null,'x','10');
img.setAttributeNS(null,'y','10');
img.setAttributeNS(null, 'visibility', 'visible');
$('svg').append(img);
like image 158
undefined Avatar answered Oct 20 '22 18:10

undefined


jQuery alone cannot handle SVG manipulation properly, as this answer explains. You should probably be using Raphael, or one of the hacky methods described in the link above.

like image 2
Chris Laplante Avatar answered Oct 20 '22 20:10

Chris Laplante