Skip to content

Instantly share code, notes, and snippets.

@Calvein
Last active December 22, 2015 19:19
Show Gist options
  • Save Calvein/6518348 to your computer and use it in GitHub Desktop.
Save Calvein/6518348 to your computer and use it in GitHub Desktop.
Get the degree of an svg line.
/*
* Draw text parallel to a line
*/
// Line
x1 = x(0)
y1 = y(0)
x2 = x(25)
y2 = y(30)
// Get the lines length
a = Math.abs(x2 - x1)
o = Math.abs(y2 - y1)
h = Math.sqrt(Math.pow(a, 2) + Math.pow(o, 2))
// Get the radian and put it as degree
deg = Math.asin(o / h) * (180 / Math.PI)
// Draw the line (hypotenuse)
el.append('line')
.attr('x1', x1)
.attr('y1', y1)
.attr('x2', x2)
.attr('y2', y2)
// Draw text parallel to the line
roi.append('text')
.text('My rotated text')
.attr('transform', 'translate(' + x2 + ',' + y2 + ')rotate(' + deg + ')')
@hughsk
Copy link

hughsk commented Sep 11, 2013

@Calvein, this is faster and means you don't need a, o and h :)

var deg = Math.atan2(y2 - y1, x2 - x1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment