arrow_back
Back

SVG lines: line element, stroke, stroke-width, and caps

Andrew Dorokhov Andrew Dorokhov schedule 2 min read

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

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

SVG ellipses: ellipse, rx, ry, rotation, and transforms

arrow_forward