HTML5实现手势屏幕解锁
|
1035次阅读|
作者:html,css
摘要:实现原理 利用HTML5的canvas,将解锁的圈圈划出,利用touch事件解锁这些圈圈,直接看代码
效果展示
实现原理
利用HTML5的canvas,将解锁的圈圈划出,利用touch事件解锁这些圈圈,直接看代码。
01 | function createCircle() { |
07 | r = ctx.canvas.width / (2 + 4 * n); |
08 | for ( var i = 0 ; i < n ; i++) { |
09 | for ( var j = 0 ; j < n ; j++) { |
canvas里的圆圈画好之后可以进行事件绑定
02 | can.addEventListener( "touchstart" , function (e) { |
03 | var po = getPosition(e); |
05 | for ( var i = 0 ; i < arr.length ; i++) { |
06 | if (Math.abs(po.x - arr[i].x) < r && Math.abs(po.y - arr[i].y) < r) { |
08 | drawPoint(arr[i].x,arr[i].y); |
09 | lastPoint.push(arr[i]); |
10 | restPoint.splice(i,1); |
15 | can.addEventListener( "touchmove" , function (e) { |
17 | update(getPosition(e)); |
20 | can.addEventListener( "touchend" , function (e) { |
24 | setTimeout( function (){ |
接着到了最关键的步骤绘制解锁路径逻辑,通过touchmove事件的不断触发,调用canvas的moveTo方法和lineTo方法来画出折现,同时判断是否达到我们所画的圈圈里面,其中lastPoint保存正确的圈圈路径,restPoint保存全部圈圈去除正确路径之后剩余的。 Update方法:
02 | ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); |
03 | for ( var i = 0 ; i < arr.length ; i++) { |
04 | drawCle(arr[i].x, arr[i].y); |
07 | drawLine(po , lastPoint); |
08 | for ( var i = 0 ; i < restPoint.length ; i++) { |
09 | if (Math.abs(po.x - restPoint[i].x) < r && Math.abs(po.y - restPoint[i].y) < r) { |
10 | drawPoint(restPoint[i].x, restPoint[i].y); |
11 | lastPoint.push(restPoint[i]); |
12 | restPoint.splice(i, 1); |
最后就是收尾工作,把路径里面的lastPoint保存的数组变成密码存在localstorage里面,之后就用来处理解锁验证逻辑了。
01 | function storePass(psw) { |
02 | if (pswObj.step == 1) { |
03 | if (checkPass(pswObj.fpassword, psw)) { |
05 | pswObj.spassword = psw; |
06 | document.getElementById( 'title' ).innerHTML = '密码保存成功' ; |
07 | drawStatusPoint( '#2CFF26' ); |
08 | window.localStorage.setItem( 'passwordx' , JSON.stringify(pswObj.spassword)); |
09 | window.localStorage.setItem( 'chooseType' , chooseType); |
11 | document.getElementById( 'title' ).innerHTML = '两次不一致,重新输入' ; |
12 | drawStatusPoint( 'red' ); |
15 | } else if (pswObj.step == 2) { |
16 | if (checkPass(pswObj.spassword, psw)) { |
17 | document.getElementById( 'title' ).innerHTML = '解锁成功' ; |
18 | drawStatusPoint( '#2CFF26' ); |
20 | drawStatusPoint( 'red' ); |
21 | document.getElementById( 'title' ).innerHTML = '解锁失败' ; |
25 | pswObj.fpassword = psw; |
26 | document.getElementById( 'title' ).innerHTML = '再次输入' ; |
解锁组件
将这个HTML5解锁写成了一个组件,放在
https://github.com/lvming6816077/H5lock