Thursday, December 23, 2010

How to draw a curve between two points in SVG ?

To draw curve in SVG, we need to provide the following information to the SVG tag's 'd' attribute.

d = "M x1 y1 Q a b x2 y2";

Here M and Q are commands,
where x1, y1, x2, y2, are source and destination co-ordinates.
where a and b are a co-ordinate, which is perpendicular to mid point of the (x1, y1) and (x2, y2)

So given that two points source (x1, y1) and Destination (x2, y2), we need to find (a, b)

so draw a straight line between (x1, y1) and (x2, y2), on that draw a perpendicular line from it's mid point. choose any x and y on that perpendicular line which is (a, b).

Now you see here first we need to find the slope of the straight line of (x1, y1) and (x2, y2) from that we need to find the slope of the perpendicular line

m = tanθ = - (y2 - y1)/(x2-x1)
so θ = atan( - (y2 - y1) / (x2 - x1) )

we need to find distance between those two points, it is
sqr(d) = sqr(x2-x1) + sqr(y2 - y1)

r = sqrt ( d )

mid point of those two co-ordinates are this
m1 = ( x1 + x2 ) / 2
m2 = ( y1 + y2 ) / 2

so now,

a = m1 + r * sin θ
b = m2 + r * cos θ

Finally we calculated a and b, now we can use it in the svg 'd' attributes

See the below picture, in the first picture the curves are drawn between two modes whose slope is zero, so
a = m1
b = m2 + r

so these a and b varies when you drag a node, so you need to calculate it for every x and y


No comments:

Post a Comment