增加曲線效果,點與點之間的線條轉折變得更加柔和,效果如下
Chart
主要增加的程式碼如下,參考chart.js繪製曲線的方式,自己試做看看,主要是針對點與點之間距離的計算出bezier curve的control point1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35for(let index=1; index<(dataLength-1); index++){
const prePoint = this._dataSet[index - 1];
const currentPoint = this._dataSet[index];
const nextPoint = this._dataSet[index + 1];
/*
use pre point p(x0, y0) and next p(x2, y2) point to calc current point p(x1, y1) offset scale
*/
const deltaX = nextPoint.x - prePoint.x;
const deltaY = nextPoint.y - prePoint.y;
const distance = this._distance(prePoint, nextPoint);
const cos = deltaX / distance;
const sin = deltaY / distance;
/*
calc current point distance between two points pre and next
*/
const preRelativeDistance = this._distance(prePoint, currentPoint);
const nextRelativeDistance = this._distance(currentPoint, nextPoint);
/*
calc actual offset by current point and pre point
ps: actual offset = current point - (scale * two point distance * tension)
*/
const preControlPointX = currentPoint.x - (cos * preRelativeDistance * this._LINE_TENSION);// _LINE_TENSION = 0.2
const preControlPointY = currentPoint.y - (sin * preRelativeDistance * this._LINE_TENSION);
/*
calc actual offset by current point and next point
*/
const nextControlPointX = currentPoint.x + (cos * nextRelativeDistance * this._LINE_TENSION);
const nextControlPointY = currentPoint.y + (sin * nextRelativeDistance * this._LINE_TENSION);
this._curveDataSet.push({
oriPoint: currentPoint,
pre: {x: preControlPointX, y: preControlPointY},
next: {x: nextControlPointX, y: nextControlPointY},
});
}
使用 bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) 繪製出曲線
其中cp1x, cp1y 第一個控制點,而cp2x, cp2y 第二個控制點,最後一組參數x, y 為繪製的終點座標
1 | for(const [index, point] of this._dataSet.entries()){ |