2015-10-26 21 views
1

我试图在屏幕中间绘制一个等边三角形顶点。使用javascript动态绘制SVG

我想要使用JavaScript,因为不同用户的屏幕尺寸可能不同,因此屏幕中心必须先找到。

这里是我的代码:

function drawRect(){ 

     var w = $(document).width(); 
     var h = $(window).height(); 
     var halfh = h/2; 
     var halfw = w/2; 
     var svg = document.createElement("svg"); 
     var poly = document.createElement("polygon"); 
     svg.setAttribute("style", "position: fixed;"); 
     svg.setAttribute("height", ""+h); 
     svg.setAttribute("width", ""+w); 
     poly.setAttribute("points", ""+halfw+","+halfh+" 0,"+h+" "+w+","+h); 
     poly.setAttribute("style", "fill:lime;stroke:purple;stroke-width:1"); 
     svg.appendChild(poly); 

     var svgplace = document.getElementById("carpet"); 
     svgplace.appendChild(svg); 
    } 

没有三角形出现在屏幕上。但是,如果我在chrome上打开'Inspect Element'控制台,并且稍微修改了创建的html元素,它就会出现! (任何一种小型的mod,像在某处添加空间一样)

请帮忙!

在此先感谢

+0

检查属性 - 没有什么改变? –

+0

检查这个帖子http://stackoverflow.com/questions/3290392/creating-svg-markers-programatically-with-javascript – LGSon

+0

你为什么要这样做?使用视图框,然后你可以有固定的坐标。 –

回答

2

您需要使用

document.createElementNS("http://www.w3.org/2000/svg", "polygon"); 

SVG是从HTML自己的命名空间预留。因此,您需要使用createElementNS创建SVG命名空间中的元素。


考虑下面的例子,在Chrome工程和Firefox

var newItem = document.createElementNS("http://www.w3.org/2000/svg", "circle"); 
 
newItem.setAttribute("cx", ((16 * 1) + 8)); 
 
newItem.setAttribute("cy", "50%"); 
 
newItem.setAttribute("r", 4); 
 
newItem.setAttribute("fill", "#333333"); 
 

 
document.getElementById("target").appendChild(newItem);
<svg id="target"> 
 
</svg>