一种连接两个点的贝塞尔曲线

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function bezier(startPoint, endPoint){
var sx = startPoint.x,
sy = startPoint.y,
ex = endPoint.x,
ey = endPoint.y,
length = Math.sqrt( Math.pow( (sx-ex), 2) + Math.pow( (sy-ey), 2 ) ) ;

//可以根据两点的倾斜方向做更加细致的取点,这里只列出其中一种方式

if ( Math.abs( sx - ex ) < 5 ){ //两个点的横坐标差值小于5,姑且认为是平行的,这里可以自行设置
return [startPoint, {x:sx-length, y:sy}, {x:ex+length, y:ey}, endPoint] ;
}
else if ( Math.abs( sy - ey ) < 5> ){ //纵坐标相同
return [startPoint, {x:sx, y:sy-length}, {x:ex, y:ey+length}, endPoint] ;
}
else { //斜率的情况
var slope = (ey-sy) / (ex-sx), //斜率
dx = Math.sqrt( Math.pow(length,2) / ( 1+ 1/(slope*slope) ) ), //x坐标变化值
dy = Math.abs(-1/slope * dx) ;
return [startPoint, {x:sx-dx, y:sy-dy}, {x:ex+dx ,y:ey+dy}, endPoint] ;
}
}

var pointArr = bezier({x:11, y:22}, {x:33, y:44});
$('svg #path').attr('d', 'M'+pointArr[0].x+' '+pointArr[0].y+' C '+pointArr[1].x+' '+pointArr[1].y+', '+pointArr[2].x+' '+pointArr[2].y+', '+pointArr[3].x+' '+pointArr[3].y);

svg path更新问题

可能有这种场景, 在插入一段svg path后, 需要更改该path的路径, 于是重新设置path 的 ‘d’ 路径path, 在F12可以看到path更改后,但页面上线条并没有改变。
普通的dom插入页面,调用.appendChild(),但svg不算dom,所以插入path,当作dom来更改无效。

##解决方法##
.createElementNS

1
2
var path = document.createElementNS('ttp://www.w3.org/2000/svg', 'path');
$(path).attr({//设置属性}).append(//)