这里实现触摸手势操作的有四个基本方向:上,下,左,右,用javascript
语言编写,可以参考下
- 笔者TA远方在一个文件名为gesture.js写了, 定义触摸操作中的所有手势,一共8个总方向,包括四个基本方向,还有一个点击,代码如下
const G = {
left: 'LEFT',
right: 'RIGHT',
down: 'DOWN',
up: 'UP',
click: 'CLICK',
leftAndUp: 'LEFT_UP',
leftAndDown: 'LEFT_DOWN',
rightAndUp: 'RIGHT_UP',
rightAndDown: 'RIGHT_DOWN',
}
- 触摸操作中,除了点击,常见的是通过计算两点不同的位置,一个是触摸开始点a,另一个是触摸结束点b,就能算出手势操作,实现方法getG如下
const getG = (g) => {
const { a, b } = g;//两点
if (a!=null && b!=null){
//offX,Y 相差值
const offX = a.x-b.x;
const offY = a.y-b.y;
//absX,Y 绝对值
const absX = Math.abs(offX);
const absY = Math.abs(offY);
//是否上下移动
if (absX < absY) {
if (a.y > b.y) {
return G.up;//向上移
} else {
return G.down;//向下移
}
} //是否左右移动
else if (absX > absY) {
if (a.x > b.x) {
return G.left;//向左
} else {
return G.right;//向右
}
} else {
//绝对值不为0,两个方向垂直之间的夹角方向移动
if (absX!=0){
if (offX>0) {
if (offY>0) {
return G.leftAndUp;//向左上方向移
} else {
return G.leftAndDown;
}
} else {
if (offY>0) {
return G.rightAndUp;//向右上方向移
} else {
return G.rightAndDown;
}
}
}
}
}
return G.click;//点击操作
}
- 最后讲下使用例子,在小程序中的canvas组件中使用触摸事件,实现手势的控制操作,代码如下
import Gesture from '@/common/js/gesture.js';
App({
data: {
gestures: {},
},
onTouchStart(event){
this.gestures.a = event.touches[0];
},
onTouchMove(event){
this.gestures.b = event.touches[0];
},
onTouchEnd(){
const g = Gesture.getG(this.gestures);
this.ctrlMove(g);
this.gestures = {};
},
ctrlMove(g){
const Ges = Gesture.G;
//...控制移动
switch(g){
case Ges.left:
//...
break;
//...
}
}
})