前段時間閑暇的時候看到一個貝塞爾曲線算法的文章,試著在小程序里去實現小程序的貝塞爾曲線算法,及其效果。
主要應用到的技術點:
1、小程序wxss布局,以及數據綁定
2、js二次bezier曲線算法
核心算法,寫在app.js里
bezier: function (points, times) {
// 0、以3個控制點為例,點A,B,C,AB上設置點D,BC上設置點E,DE連線上設置點F,則最終的貝塞爾曲線是點F的坐標軌跡。
// 1、計算相鄰控制點間距。
// 2、根據完成時間,計算每次執行時D在AB方向上移動的距離,E在BC方向上移動的距離。
// 3、時間每遞增100ms,則D,E在指定方向上發生位移, F在DE上的位移則可通過AD/AB = DF/DE得出。
// 4、根據DE的正余弦值和DE的值計算出F的坐標。
// 鄰控制AB點間距
var bezier_points = [];
var points_D = [];
var points_E = [];
const DIST_AB = Math.sqrt(Math.pow(points[1]['x'] - points[0]['x'], 2) + Math.pow(points[1]['y'] - points[0]['y'], 2));
// 鄰控制BC點間距
const DIST_BC = Math.sqrt(Math.pow(points[2]['x'] - points[1]['x'], 2) + Math.pow(points[2]['y'] - points[1]['y'], 2));
// D每次在AB方向上移動的距離
const EACH_MOVE_AD = DIST_AB / times;
// E每次在BC方向上移動的距離
const EACH_MOVE_BE = DIST_BC / times;
// 點AB的正切
const TAN_AB = (points[1]['y'] - points[0]['y']) / (points[1]['x'] - points[0]['x']);
// 點BC的正切
const TAN_BC = (points[2]['y'] - points[1]['y']) / (points[2]['x'] - points[1]['x']);
// 點AB的弧度值
const RADIUS_AB = Math.atan(TAN_AB);
// 點BC的弧度值
const RADIUS_BC = Math.atan(TAN_BC);
// 每次執行
for (var i = 1; i <= times; i++) {
// AD的距離
var dist_AD = EACH_MOVE_AD * i;
// BE的距離
var dist_BE = EACH_MOVE_BE * i;
// D點的坐標
var point_D = {};
point_D['x'] = dist_AD * Math.cos(RADIUS_AB) + points[0]['x'];
point_D['y'] = dist_AD * Math.sin(RADIUS_AB) + points[0]['y'];
points_D.push(point_D);
// E點的坐標
var point_E = {};
point_E['x'] = dist_BE * Math.cos(RADIUS_BC) + points[1]['x'];
point_E['y'] = dist_BE * Math.sin(RADIUS_BC) + points[1]['y'];
points_E.push(point_E);
// 此時線段DE的正切值
var tan_DE = (point_E['y'] - point_D['y']) / (point_E['x'] - point_D['x']);
// tan_DE的弧度值
var radius_DE = Math.atan(tan_DE);
// 地市DE的間距
var dist_DE = Math.sqrt(Math.pow((point_E['x'] - point_D['x']), 2) + Math.pow((point_E['y'] - point_D['y']), 2));
// 此時DF的距離
var dist_DF = (dist_AD / DIST_AB) * dist_DE;
// 此時DF點的坐標
var point_F = {};
point_F['x'] = dist_DF * Math.cos(radius_DE) + point_D['x'];
point_F['y'] = dist_DF * Math.sin(radius_DE) + point_D['y'];
bezier_points.push(point_F);
}
return {
'bezier_points': bezier_points
};
}
注釋很詳細,算法的原理其實也很簡單。 源碼也發出來吧,github地址:https://github.com/xiongchenf/flybus.git
調用方法和用法就不占篇幅了,都是基礎的東西。效果圖如下: