Javascript动态创建SVG在IE、Firefox下不显示

近来同事在做HTML5项目画图时用到了SVG,SVG是用Javascript生成的,遇到在Chrome下能显示画出的内容,而在IE、Firefox上则是空白的。用firebug等工具查看生成的html对象,该有的元素都有。把代码copy到 http://www.w3schools.com/SVG/tryit.asp?filename=trysvg_text 上也能正常显示,各种无语中。。。

开始的代码如下:

var svg = document.createAttributeNS(NS, "svg");
var text = document.createElementNS(NS, "text");
text.setAttribute("stroke", "#007AB1");
text.setAttribute("stroke-width", "0.5");
text.setAttribute("font-size", "11");
text.setAttribute("x", baseBottomPoint.x - 10);
text.setAttribute("y", baseBottomPoint.y);
text.setAttribute("class", "patternRecognitionHideItem");
text.setAttribute("together", this.together);
var textContent = '<tspan x="0" dy="15">hello1</tspan><tspan stroke="black" x="0" dy="13">hello2</tspan>';
$(text).html(textContent);
$(svg).append(text);

经过各种谷歌度娘,最后发现问题出在Namespace上, 直接用 $(text).html(textContent) 产生的控件svg不会渲染。

 

最后的代码:

var svg = document.createAttributeNS(NS, "svg");
var text = document.createElementNS(NS, "text");
text.setAttribute("stroke", "#007AB1");
text.setAttribute("stroke-width", "0.5");
text.setAttribute("font-size", "11");
text.setAttribute("x", baseBottomPoint.x - 10);
text.setAttribute("y", baseBottomPoint.y);

//创建带namespace的控件,控件内的text也需要使用svc document动态创建成TextNode
var tspan = document.createElementNS(NS, "tspan");
tspan.setAttribute("x", x);
tspan.setAttribute("dy", dy);
//多个空格需要使用 \x20\xa0
var textNode = svcdoc.createTextNode(“hello \x20\xa0\x20\xa0\x20\xa0”); tspan.appendChild(textNode); $(svg).append(text);

 

SVG帮助方法

      function getSVGDocument(svg) {
                var result = null;
         //如果是IE  
if (!+[1,]) { if (svg.tagName.toLowerCase() == "embed") { try { result = svg.getSVGDocument(); } catch (e) { alert(e + " may be svg embed not init"); } } } else { result = svg.ownerDocument; } return result; }
function  getSVGRoot(svg, doc) { if (svg.tagName.toLowerCase() == "embed") { if (doc) { return doc.documentElement; } else { return thisgetSVGDocument(svg).documentElement; } } else if (svg.tagName.toLowerCase() == "svg") { return svg; } return null; }

 

 参考网页:

http://www.kevlindev.com/tutorials/basics/text/js_dom/

posted @ 2014-04-24 18:21  杂货匠工  Views(1747)  Comments(0)    收藏  举报