简体   繁体   中英

javascript - find coefficient/function for given points on cubic bezier curve


I'm creating a simple d3 graph based on this infographic : http://bit.ly/1o4iGfK

What I'm trying to reproduce right now is the cubic bezier lines between each of my "nodes".
I've drawn a curve thanks to this website . So I know the x and y coordinates of each four points :
(x0, y0) = (32, 45);
(x1, y1) = (32, 150);
(x2, y2) = (190, 150);
(x3, y3) = (190,260);

But I don't really know how to use the common algorithms, and transpose it as a javascript function so that I could only write known (x0,y0) and (x3, y3) coordinates, and pouf! get a pretty line.
Mostly because I'm not really good with algebra. Sorry.

I've found this thread : here
It seems to be part of the answer but, well, I don't fully understand the code and the explications.

For now I've used this function :

function linkArc(d) {
            var dx = d.source.x - d.target.x,
                dy = d.source.y - d.target.y,
                dr = Math.sqrt(dx * dx + dy * dy);

            return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + "    0    0,1 " + d.target.x + "," + d.target.y;
        }

Which is a simple arc, not really what I'm looking for.
(d.source.x , d.target.y) : coordinates of the first point (x0,y0)
(d.target.x , d.target.y) : coordinates of the end point (x3, y3)

Thanks.

What you want is a vertical slope at the end points. Since the inner control points determine the slope, you have to set them directly above and below the control points. There are two degrees of freedom in how much above and below. For instance, put them at the thirds of the height difference

x1 = x0;  y1 = (2*y0+y3)/3;
x2 = x3;  y2 = (2*y3+y0)/3;

The general scheme is

y1 = (a*y0+b*y3)/(a+b);
y2 = (a*y3+b*y0)/(a+b);

where

y1-y0 = b/(a+b)*(y3-y0)

so that b/(a+b) is the height fraction that the first control point is above the zeroth endpoint.


So to get a fraction of 2/3 instead of the 1/3 above, use a=1 and b=2 to get

y1=(y0+2*y3)/3;
y2=(y3+2*y0)/3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM