Points drawn in the onload event of an SVG element are NOT displayed during rendering

I am working on drawing an SVG grid using Javascript. I managed to get the axis, as well as my square marks. However, I ran into the problem of adding my dynamic points.

I am trying to draw dots in the onload event of an SVG element. Using Firebug, I was able to confirm that the circle elements representing my points were added to the SVG DOM with the correct attributes set for the location, brush, etc.

Unfortunately, the actual image displayed by my browser (Firefox 3) is not updated to reflect the fact that I added these new DOM elements!

Below is the code that I use to add elements to the correct DOM node:

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); } } 

The SVG structure afterwards, as shown by the Firebug debug extension for Firefox:

 <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> 

Any help would be greatly appreciated, I'm a complete SVG newbie!

+4
source share
1 answer

To dynamically create SVG elements, you must use the createElementNS method with an appropriate namespace, for example

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

For more information, see Kevin Lindsay's tutorials and especially here .

+5
source

All Articles