Search code examples
svgline

SVG line in y=mx+c format


I want to draw an SVG line given the slope and the constant term or the y = mx + c format.

Is there a direct way to do this in SVG or an indirect way?

Thanks in advance.


Solution

  • The <line> tag only supports start and end attributes (x1, y1, x2, y2). As such, you'll need to pick x coordinates outside your canvas manually and use y2 = y1 + m(x2 - x1).

    Edit

    Looking through the spec, it's possible to transform individual elements as required:

    <line ... transform="translate(x, y) rotate(theta)" />
    

    Where theta is the angle of clockwise rotation in degrees.

    So you could draw a long horizontal line from (-10000, 0) to (10000, 0), say, and then apply the appropriate rotation and translation to position it:

    <line x1="-10000" y1="0" x2="10000" y2="0" transform="translate(150, 200) rotate(-30)" />
    

    Will draw a (seemingly endless) line through (150, 200) of slope π/6 radians.