我正在尝试绘制一个isoceles三角形,它的顶部顶点位于屏幕中间。
我想使用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。就像在中间某处添加空间一样)
请帮忙!
提前致谢
I'm trying to draw an isoceles triangle with it's top vertex in the middle of the screen.
I want to use JavaScript as screen sizes of different users can be different and hence, center of the screen must first be found out.
Here is my code:
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); }No triangle appears on the screen. But, if I open the 'Inspect Element' console on chrome, and I modify the created html element slightly, it appears! (Any kind of small mod. Like adding a space in the middle somewhere)
Please help!
Thanks in advance
最满意答案
你需要使用
document.createElementNS("http://www.w3.org/2000/svg", "polygon");除了HTML之外, SVG还有自己的命名空间。 因此,您需要使用createElementNS创建SVG名称空间中的createElementNS 。
请考虑以下适用于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>You need to be using
document.createElementNS("http://www.w3.org/2000/svg", "polygon");SVG is in its own namespace aside from HTML. Therefore, you need to create elements that are in the SVG namespace using createElementNS.
Consider the following example that works in Chrome and 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>
更多推荐
发布评论