我正在使用Javascript绘制SVG网格。我已设法绘制轴,以及我的象限标签。但是我在添加动态点时遇到了一个问题。

我正在尝试在SVG元素的onload事件中绘制点。当使用Firebug时,我已经能够确认代表我的点的圆形元素被添加到SVG DOM中,并为位置,画笔描边等设置了正确的属性。

不幸的是,我的浏览器(Firefox 3)渲染的实际图像没有更新,以反映我添加了这些新DOM元素的事实!

以下是我用于将元素添加到正确DOM节点的代码:

function drawPoints()
  {
    var points = pointCollection.points;
    var grid = SVGDoc.getElementById("gridGroup");

    for(var i = 0 in points)
    {
        var x = points[i].x;
        var y = points[i].y;
        var label = points[i].event;

        //<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>

        var dot = SVGDoc.createElement("circle");
        dot.setAttribute("cx", x);
        dot.setAttribute("cy", y);
        dot.setAttribute("r", 15);
        dot.setAttribute("stroke", "red");
        dot.setAttribute("stroke-width", "2");
        dot.setAttribute("fill", "black");

        grid.appendChild(dot);
    }
  }

之后的SVG结构如Firefox的Firebug调试扩展所示:

<svg width="800" height="800" version="1.1" xmlns="http://www.w3.org/2000/svg" onload="init(evt); drawAxis(); drawPoints()">
  <g id="gridGroup" stroke="green">
    <line id="xAxis" x1="0" x2="800" y1="400" y2="400" stroke-width="2"/>
    <line id="yAxis" x1="400" x2="400" y1="0" y2="800" stroke-width="2"/>
    <text id="importantLabel" x="155" y="20" font-family="Verdana" font-size="18" fill="blue" onclick="drawPoints()">Important</text>
    <text id="notImportantLabel" x="555" y="20" font-family="Verdana" font-size="18" fill="blue">Not-Important</text>
    <text id="urgentLabel" x="20" y="200" font-family="Verdana" font-size="18" fill="blue" transform="rotate(-90, 20, 200)">Urgent</text>
    <text id="notUrgentLabel" x="20" y="600" font-family="Verdana" font-size="18" fill="blue" transform="rotate(-90, 20, 600)">Not-Urgent</text>

    <circle cx="30" cy="30" r="15" stroke="red" stroke-width="2" fill="black"/>
    <circle cx="600" cy="600" r="15" stroke="red" stroke-width="2" fill="black"/>
    <circle cx="400" cy="400" r="15" stroke="red" stroke-width="2" fill="black"/>
  </g>
</svg>

任何帮助将不胜感激,我是一个完整的SVG新手!

有帮助吗?

解决方案

为了动态创建SVG元素,您必须将 createElementNS 方法与适当的命名空间一起使用,例如

var dot = SVGDoc.createElementNS("http://www.w3.org/2000/svg", "circle");

有关详细信息,请参阅 Kevin Lindsay的教程,尤其是这里

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top