標籤:螢幕解鎖 store tle 邏輯 scope return length title 利用
實現原理
利用HTML5的canvas,將解鎖的圈圈划出,利用touch事件解鎖這些圈圈,直接看代碼。
- function createCircle(){// 建立解鎖點的座標,根據canvas的大小來平均分配半徑
-
- var n = chooseType;// 畫出n*n的矩陣
- lastPoint = [];
- arr = [];
- restPoint = [];
- r = ctx.canvas.width / (2 + 4 * n);// 公式計算 半徑和canvas的大小有關
- for (var i = 0 ; i < n ; i++) {
- for (var j = 0 ; j < n ; j++) {
- arr.push({
- x: j * 4* r + 3 * r,
- y: i * 4* r + 3 * r
- });
- restPoint.push({
- x: j * 4* r + 3 * r,
- y: i * 4* r + 3 * r
- });
- }
- }
- //return arr;
- }
複製代碼
canvas裡的圓圈畫好之後可以進行事件綁定
- function bindEvent() {
- can.addEventListener("touchstart", function (e) {
- var po = getPosition(e);
- console.log(po);
- for (var i = 0 ; i < arr.length ; i++) {
- if (Math.abs(po.x - arr[i].x)< r && Math.abs(po.y - arr[i].y) < r) { // 用來判斷起始點是否在圈圈內部
-
- touchFlag= true;
- drawPoint(arr[i].x,arr[i].y);
- lastPoint.push(arr[i]);
- restPoint.splice(i,1);
- break;
- }
- }
- }, false);
- can.addEventListener("touchmove", function (e) {
- if (touchFlag) {
- update(getPosition(e));
- }
- }, false);
- can.addEventListener("touchend", function (e) {
- if (touchFlag) {
- touchFlag = false;
- storePass(lastPoint);
- setTimeout(function(){
-
- init();
- }, 300);
- }
-
-
- }, false);
- }
複製代碼
接著到了最關鍵的步驟繪製解鎖路徑邏輯,通過touchmove事件的不斷觸發,調用canvas的moveTo方法和lineTo方法來畫出折現,同時判斷是否達到我們所畫的圈圈裡面,其中lastPoint儲存正確的圈圈路徑,restPoint儲存全部圈圈去除正確路徑之後剩餘的。 Update方法:
- function update(po) {// 核心變換方法在touchmove時候調用
- ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
-
- for (var i = 0 ; i < arr.length ; i++) { // 每幀先把面板畫出來
- drawCle(arr[i].x, arr[i].y);
- }
-
- drawPoint(lastPoint);// 每幀花軌跡
- drawLine(po , lastPoint);// 每幀畫圓心
-
- for (var i = 0 ; i < restPoint.length ; i++) {
- if (Math.abs(po.x - restPoint[i].x) < r&& Math.abs(po.y - restPoint[i].y) < r) {
- drawPoint(restPoint[i].x,restPoint[i].y);
- lastPoint.push(restPoint[i]);
- restPoint.splice(i, 1);
- break;
- }
- }
-
- }
複製代碼
最後就是收尾工作,把路徑裡面的lastPoint儲存的數組變成密碼存在localstorage裡面,之後就用來處理解鎖驗證邏輯了。
- function storePass(psw){// touchend結束之後對密碼和狀態的處理
- if (pswObj.step == 1) {
- if (checkPass(pswObj.fpassword, psw)) {
- pswObj.step = 2;
- pswObj.spassword = psw;
- document.getElementById(‘title‘).innerHTML = ‘密碼儲存成功‘;
- drawStatusPoint(‘#2CFF26‘);
- window.localStorage.setItem(‘passwordx‘, JSON.stringify(pswObj.spassword));
- window.localStorage.setItem(‘chooseType‘, chooseType);
- } else {
- document.getElementById(‘title‘).innerHTML = ‘兩次不一致,重新輸入‘;
- drawStatusPoint(‘red‘);
- delete pswObj.step;
- }
- } else if (pswObj.step == 2) {
- if (checkPass(pswObj.spassword, psw)) {
- document.getElementById(‘title‘).innerHTML = ‘解鎖成功‘;
- drawStatusPoint(‘#2CFF26‘);
- } else {
- drawStatusPoint(‘red‘);
- document.getElementById(‘title‘).innerHTML = ‘解鎖失敗‘;
- }
- } else {
- pswObj.step = 1;
- pswObj.fpassword = psw;
- document.getElementById(‘title‘).innerHTML = ‘再次輸入‘;
- }
-
- }
手機螢幕解鎖