Saturday, 15 May 2010

javascript - Get coordinates of line-surrounding box -



javascript - Get coordinates of line-surrounding box -

i've been working in javascript code line drawing system. i'd lines drawn selectable, i've been attempting implement line-highlighting. can see in image below, have line (in black) known coordinates , equation in slope-intercept (y=mx+b). how can calculate corners' (circled in green) coordinates, knowing box's radius?

this easiest think of in terms of vectors.

start off defining point @ end of line a, , other end b

var = new vector(1, 1) var b = new vector(5, 3)

now find unit direction vector of line (a vector of length 1 pointing b), , perpendicular:

var dir = b.minus(a).normalize(); var dir_perp = new vector(dir.y, -dir.x)

and extend them of length thickness:

dir = dir.times(thickness); dir_perp = dir_perp.times(thickness)

the 4 corners then:

[ a.minus(dir).plus(dir_perp), a.minus(dir).minus(dir_perp), b.plus(dir).minus(dir_perp), b.plus(dir).plus(dir_perp) ]

this assumes have sort of vector math library. here's 1 made earlier

javascript math line coordinates

No comments:

Post a Comment