首先,需要获取向量的旋转方向和角度。
//这两个方法属于向量计算,具体原理请阅读本文最后的参考文献
_getRotateDirection(vector1,vector2) {
return vector1.x * vector2.y - vector2.x * vector1.y;
}
_getRotateAngle(vector1,vector2) {
let direction = this._getRotateDirection(vector1,vector2);
direction = direction > 0 ? -1 : 1;
let len1 = this._getDistance(vector1.x,vector1.y);
let len2 = this._getDistance(vector2.x,vector2.y);
let mr = len1 * len2;
if(mr === 0) return 0;
let dot = vector1.x * vector2.x + vector1.y * vector2.y;
let r = dot / mr;
if(r > 1) r = 1;
if(r < -1) r = -1;
return Math.acos(r) * direction * 180 / Math.PI;
}
然后,我们在手指发生移动时,调用获取旋转方向和角度的方法。
_onTouchStart(e) {
...
if(e.touches.length > 1) {
this.touchVector = {
x: point2.pageX - this.startX,
y: point2.pageY - this.startY
};
}
...
}
_onTouchMove(e) {
...
if(this.touchVector) {
let vector = {
x: e.touches[1].pageX - e.touches[0].pageX,
y: e.touches[1].pageY - e.touches[0].pageY
};
let angle = this._getRotateAngle(vector,this.touchVector);
this._emitEvent('onRotate',{
angle
});
this.touchVector.x = vector.x;
this.touchVector.y = vector.y;
}
...
}
实战