How to create a curved SVG path between two points?

后端 未结 1 608
广开言路
广开言路 2020-12-30 08:45

I need to draw a symmetrically curved line between the centers of two circles.


    

        
1条回答
  •  醉酒成梦
    2020-12-30 09:08

    An SVG quadratic curve will probably suffice. To draw it, you need the end points (which you have) and a control point which will determine the curve.

    To make a symmetrical curve, the control point needs to be on the perpendicular bisector of the line between the end points. A little maths will find it.

    So, from two points...

    you can get to

    with the code in

    
        
        
        	
        	
        	
        	
        
        
        	
        		
        		
        		
        		
        	
        	
        
        

    If you want the curve to go the other way, change the sign of offset.

    If you are using ES6-compliant browsers, you can use string interpolation for slightly tidier code:

    var curve = `M${p1x} ${p1y} Q${c1x} ${c1y} ${p2x} ${p2y}`;
    

    There is no requirement for the control point to be shown - that's just so you can see where it is and illustrate that the curve doesn't go through it.

    Note: an alternative to using atan2 is to calculate the negative reciprocal of the gradient of the line between the points, but that is fiddly for the case where the gradient is zero and may produce wildly inaccurate results when the gradient is close to zero.

    0 讨论(0)
提交回复
热议问题