Today I learned about SVG lines. Why would you wanna draw lines using code? Why not just use a paintbrush app? Or Presentation software to draw shapes (including lines)? Because…

  1. We want to draw shapes directly on a webpage without having to paste images of drawings from other softwares.
  2. We want to associate large amount of data with different shapes to show fancy graphs on the webpage. Associating data with lines, circles etc. can allow us to visualize complex and large data

I knew SVG lines existed but never really stepped outside of the usual shapes like rectangle, circle and text as they have seemed most useful to represent data. But then finally a situation arose that required me to draw lines on scatterplot.

Syntax is pretty simple:

<svg width="120" height="120">
<line x1="23" y1="56" x2="45" y2="56"></line>
</svg>

Inside an svg element, we just drew a straight line parallel to the webpage that starts at 23px within the SVG and runs for 33px. It’s parallel because we kept the y1 and y2 exactly the same.

To make the line pretty, one should add the properties stroke (which is basically color of the line) and stroke-width (to make it thicker). But what if you wanted dotted lines instead? stroke-dasharray has you covered. It gives you the freedom to make all kinds of dashed lines. Here is an example:

<svg width="120" height="120">
<line x1="23" y1="56" x2="45" y2="56" stroke="red" stroke-width=3 stroke-dasharray="5,10"/>
</svg>

That 5,10 value inside stroke-dasharray property basically tells the webpage that the length of dash should be 5 while the gap between dashes should be of length 10.

What if you wanted to rotate the line? just add the property transform with the value of rotate funtion ! Following would rotate the line 60 degrees counter clockwise.

<svg width="120" height="120">
<line x1="23" y1="56" x2="45" y2="56" stroke="red" stroke-width=3 stroke-dasharray="5,10" transform="rotate(-60)"/>
</svg>

You have to be careful with this though. Because only using rotate(-60) would rotate the line around the default origin of the coordinate system. This could make your line go outside the svg element. Hence a better idea would be to add x & y values for the origin along with the rotate angle. Like this:

<svg width="120" height="120">
<line x1="23" y1="56" x2="45" y2="56" stroke="red" stroke-width=3 stroke-dasharray="5,10" transform="rotate(-60 50 20)"/>
</svg>

If you want to play around with this tiny code and experiment with the line, go here.