Programmatically creating an SVG image element with javascript

守給你的承諾、 提交于 2019-11-28 04:57:01

SVG native attributes (not including xlink:href) do not share the SVG namespace; you can either use just setAttribute instead of setAttributeNS, or use

svgimg.setAttributeNS(null,'x','0');

for example.

Here it is, working: http://jsfiddle.net/UVFBj/8/

Note that I changed your fiddle to properly use XHTML, so that SVG works nicely within it in all major browsers.

For futher reference.

I've been using the function bellow to create SVG elements and it was failing to create images because of the xlink:href.

The code bellow is corrected to do that (create any svg element on the fly)

function makeSVG(parent, tag, attrs) {
            var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
            for (var k in attrs){
                if(k=="xlink:href"){
                    el.setAttributeNS('http://www.w3.org/1999/xlink', 'href', attrs[k]);
                }else{
                    el.setAttribute(k, attrs[k]);
                }
            }
        }

Sample usage:

makeSVG('#map-tiles', 'image', { class:'map-tile', 'xlink:href':'map/xxx.jpg', width:'512px', height: '512px' x:'0', y:'0'});

The parent is used to organize 'layers' on svg groups tag.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!