<!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>