Dorokhov.codes
Drawing lines
<line>
represents a straight segment connecting two points.
A line’s geometry is defined by four attributes: x1 and y1 give the coordinates of the starting point, while x2 and y2 give the coordinates of the end point.
The following code describes a diagonal line from (0,100) to (100,0):
<line x1="0" y1="100" x2="100" y2="0" stroke="black" />
Drawing using JavaScript:
<svg xmlns="http://www.w3.org/2000/svg" xml:lang="en" height="10cm" width="10cm">
...
</svg>
(function() {
var size = 10;
var doc = document;
var svg = doc.documentElement;
var svgNS = svg.namespaceURI;
if (!(svg.classList && svg.classList.contains("initialized") ))
draw();
function draw(){
var l1, l2;
for (var i = 0; i <= size; i++) {
l1 = doc.createElementNS(svgNS, "line");
l1.setAttribute("x1", i + "cm" );
l1.setAttribute("x2", size + "cm" );
l1.setAttribute("y2", i + "cm" );
svg.appendChild(l1);
l2 = doc.createElementNS(svgNS, "line");
l2.setAttribute("y1", i + "cm" );
l2.setAttribute("x2", i + "cm" );
l2.setAttribute("y2", size + "cm" );
svg.appendChild(l2);
}
if (svg.classList)
svg.classList.add("initialized");
}
})();
In some browsers, if you save a web page that was generated from a script, the saved page will include both the generated elements and the script. When you reopen the saved file, the script runs again, doubling all the generated elements. (Other browsers save the raw source code.)
if (!(svg.classList && svg.classList.contains("initialized") ))
This line tests to see if the SVG has already been initialized, and only draws the graphic if it
hasn’t. Before using the DOM 3 classList
object, it checks to confirm it exists, avoiding errors on older platforms.