<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>H5刮刮卡</title> <style> *{ padding:0; margin:0; border:none; } .card_view{ width: 200px; height: 100px; line-height: 100px; font-size: 30px; text-align: center; font-weight: bold; position: absolute; color: red; top:100px; left: 100px; } #cardCanvas{ border:1px solid #ccc; position: absolute; top:100px; left: 100px; } </style> </head> <body> <div class="card_view"> 10000元 </div> <canvas id="cardCanvas"></canvas> <script> document.querySelector(‘body‘).addEventListener(‘touchstart‘, function (e) { var e=e||window.event; e.preventDefault(); }); var c=document.getElementById(‘cardCanvas‘); var ctx=c.getContext(‘2d‘); c.width=200; //画布宽 c.height=100; //画布高 ctx.beginPath(); //画布的第一层 ctx.fillStyle="#888"; ctx.fillRect(0,0,200,100); ctx.closePath(); //画布的第二层 ctx.font="bold 50px Microsoft Yahei"; ctx.textAlign="left"; ctx.fillStyle="#666666"; ctx.fillText("刮一刮",25,60); ctx.globalCompositeOperation="destination-out"; //新图像和原图像重合部分变透明 //移动端 c.addEventListener(‘touchstart‘,function(e){ var e=e||window.event; var x=e.touches[0].clientX-c.offsetLeft; var y=e.touches[0].clientY-c.offsetTop; ctx.moveTo(x,y) c.addEventListener(‘touchmove‘,gmove,false) },false) c.addEventListener(‘touchend‘,function(){ clearC(); },false) //PC端 c.addEventListener(‘mousedown‘,function(e){ var e=e||window.event; var x=e.clientX-c.offsetLeft; var y=e.clientY-c.offsetTop; ctx.moveTo(x,y) c.addEventListener(‘mousemove‘,gmove,false) },false) c.addEventListener(‘mouseup‘,function(){ clearC(); c.removeEventListener(‘mousemove‘,gmove,false) },false) function gmove(e){ //刮卡函数 if(typeof e.touches!=‘undefined‘){ e=e.touches[0]; } var mx=e.clientX-c.offsetLeft; var my=e.clientY-c.offsetTop; ctx.strokeStyle="white"; ctx.lineCap="round"; //绘制的线结束时为圆形 ctx.lineJoin="round"; //当两条线交汇时创建圆形边角 ctx.lineWidth=20; ctx.lineTo(mx,my); ctx.stroke(); } function clearC(){ //刮开一定面积执行擦除画布函数 var data=ctx.getImageData(0,0,c.width,c.height).data; for(var i=0,j=0;i<data.length;i+=4){ //data.length=c.width*c.heigth*4,一个像素块是一个对象RGBA四个值,A范围为0~255 if(data[i]&&data[i+1]&&data[i+2]&&data[i+3]){ //存在imageData对象时j加1 PS:该像素区域透明即为不存在该对象 j++; } } if(j<=c.width*c.height*0.2){ //超过canvas面积的20%,就清除画布 ctx.clearRect(0,0,c.width,c.height); } } </script> </body> </html>
时间: 2024-10-20 10:17:11