H5核心技術---canvas實現刮刮卡
阿新 • • 發佈:2021-09-29
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"> <title></title> <style> * { margin: 0; padding: 0; } html, body{ height: 100%; overflow: hidden; } /* 繼承 */ #guguka, .images { height: 100%; } #guguka>.images { background-image: url(./1.png); background-size: 100% 100%; } #canvas { position: absolute; top: 0; left: 0; transition:1s; } </style> </head> <body> <div id="guguka"> <canvas id="canvas"></canvas> <div class="images"></div> </div> </body> <script> const canvas = document.querySelector('#canvas') var ctx = canvas.getContext('2d') canvas.width = document.documentElement.clientWidth canvas.height = document.documentElement.clientHeight var img = new Image() img.src = '2.jpg' img.onload = function() { ctx.drawImage(img, 0, 0, canvas.width, canvas.height) var flag =0; canvas.addEventListener('touchstart', function(e) { e = e || event let Touches = e.changedTouches[0] let x = Touches.clientX - canvas.offsetLeft let y = Touches.clientY - canvas.offsetTop ctx.globalCompositeOperation = "destination-out"; ctx.lineWidth = 40; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.save(); ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + 1, y + 1) ctx.stroke(); ctx.restore(); }) canvas.addEventListener('touchmove', function(e) { e = e || event let Touches = e.changedTouches[0] let x = Touches.clientX - canvas.offsetLeft let y = Touches.clientY - canvas.offsetTop ctx.save() ctx.lineTo(x, y) ctx.stroke() ctx.restore() }) canvas.addEventListener('touchend',function(e){ var imgData = ctx.getImageData(0,0,canvas.width,canvas.height) //拿到所有的畫素點的總值 var allPx = imgData.width * imgData.height; // 判斷嘛,如果一個畫素點變成透明就flag++嘛 for(var i=0;i<allPx;i++){ if(imgData.data[4*i+3]===0){ flag++; } // 判斷嘛,當flag透明的畫素點大於所有畫素點的30/36的時候就將canvas的透明度設定為0嘛 if(flag>=allPx/36*30){ canvas.style.opacity=0; //然後在CSS設定個transition:1s;嘛 } } }) // 最後動畫結束之後把canvas這個節點刪除了嘛 canvas.addEventListener('transitionend',function(){ console.log(this) this.remove(); }) } </script> </html>