canvas实现手机的手势解锁的步骤详细

2020-04-25 07:29:25易采站长站整理

for(var i=0;i<self.arr.lenth;i++){
if(Math.abs(po.x-self.arr[i].x)<self.r && Math.abs(po.y-self.arr[i].y)<self.r){
self.touchFlag=true;//允许拖拽
self.lastPoint.push(self.arr[i]);//点击过的点
self.restPoint.splice(i,1);//剩下的点剔除这个被点击的点
break;
}
}
},false);

判断是否在圆内的原理:

圆心的x轴偏移和鼠标点的x轴偏移的距离的绝对值小于半径

并且

圆心的y轴偏移和鼠标点的y轴偏移的距离的绝对值小于半径

则可以判断鼠标位于圆内

给touchmove绑定事件,在触摸点移动时给点击过的圆画上实心圆,并画线


//触摸点移动时的动画
canvasLock.prototype.update=function(po){
//清屏,canvas动画前必须清空原来的内容
this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);

//以给定坐标点为圆心画出所有圆
for(var i=0;i<this.arr.length;i++){
this.drawCircle(this.arr[i].x,this.arr[i].y);
}

this.drawPoint();//点击过的圆画实心圆
this.drawLine(po);//画线

}

//画实心圆
canvasLock.prototype.drawPoint=function(){
for(var i=0;i<this.lastPoint.length;i++){
this.ctx.fillStyle="#abcdef";
this.ctx.beginPath();
this.ctx.arc(this.lastPoint[i].x,this.lastPoint[i].y,this.r/2,0,2*Math.PI,true);
this.ctx.closePath();
this.ctx.fill();
}
}

//画线
canvasLock.prototype.drawLine=function(po){
this.ctx.beginPath();
this.lineWidth=3;
this.ctx.moveTo(this.lastPoint[0].x,this.lastPoint[0].y);//线条起点
for(var i=1;i<this.lastPoint.length;i++){
this.ctx.lineTo(this.lastPoint[i].x,this.lastPoint[i].y);
}
this.ctx.lineTo(po.x,po.y);//触摸点
this.ctx.stroke();
this.ctx.closePath();
}

效果图

4、canvas手势链接操作实现

在touchmove中补充当碰到下一个目标圆时的操作


//碰到下一个圆时只需要push到lastPoint当中去
for(var i=0;i<this.restPoint.length;i++){
if((Math.abs(po.x-this.restPoint[i].x)<this.r) && (Math.abs(po.y-this.restPoint[i].y)<this.r)){
this.lastPoint.push(this.restPoint[i]);//将这个新点击到的点存入lastPoint
this.restPoint.splice(i,1);//从restPoint中剔除这个新点击到的点
break;
}
}

效果图

5、解锁成功与否的判断


//设置密码
canvasLock.prototype.storePass=function(){
if(this.checkPass()){
document.getElementById("title").innerHTML="解锁成功";