Create svg arcs between two points

前端 未结 3 1933
死守一世寂寞
死守一世寂寞 2021-02-03 23:57

I want to connect two SVG points (e.g. the centers of two circles) using arcs. If there is only one connection, the line () will be straight. I

3条回答
  •  难免孤独
    2021-02-04 00:48

    Here is a solution that uses arcs, as asked for, rather than quadratic curves.

    // Internal function
    function connectInternal(x1,y1,x2,y2,con){
     var dx=x2-x1
     var dy=y2-y1
     var dist=Math.sqrt(dx*dx+dy*dy)
     if(dist==0 || con==0){
      return "M"+x1+","+y1+"L"+x2+","+y2
     }
     var xRadius=dist*0.75
     var yRadius=dist*0.3*(con*0.75)
     var normdx=dx/dist
     if(normdx<-1)normdx=-1
     if(normdx>1)normdx=1
     var angle=Math.acos(normdx)*180/Math.PI
     if(x1>x2){
      angle=-angle
     }
     return "M"+x1+","+y1+"A"+xRadius+","+yRadius+","+
       angle+",00"+x2+","+y2+
       "M"+x1+","+y1+"A"+xRadius+","+yRadius+","+
       angle+",01"+x2+","+y2
    }
    
    // Returns an SVG path that represents
    // "n" connections between two points.
    function connect(x1,y1,x2,y2,n){
     var ret=""
     var con=n
     if(con%2==1){
      ret+=connectInternal(x1,y1,x2,y2,con)
      con-=1
     }
     for(var i=2;i<=con;i+=2){
      ret+=connectInternal(x1,y1,x2,y2,i)
     }
     return ret
    }
    

提交回复
热议问题