当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 小程序二次贝塞尔曲线实现购物车商品曲线飞入效果

小程序二次贝塞尔曲线实现购物车商品曲线飞入效果

2019年06月01日  | 移动技术网IT编程  | 我要评论

前段时间闲暇的时候看到一个贝塞尔曲线算法的文章,试着在小程序里去实现小程序的贝塞尔曲线算法,及其效果。

主要应用到的技术点:
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

调用方法和用法就不占篇幅了,都是基础的东西。效果图如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网