其实这个问题,一直以来都不是问题,因为以前用canvas做的擦除都是针对手机满屏幕来擦除,所以一直没有踩到这个坑~~~
网络上的擦除效果其实写的都挺泛泛的,没有特别详细的,这里给你们贴一下擦除的源代码,顺便把坑也给你们先预填了,嘿嘿。
这里面最大的坑就是,如果只是擦除一小部分的时候,你就需要将canvas进行定位移动,但是移动后,canvas里的画笔也会进行一起位移。所以在canvas移动后,需要给画笔重新定位,定回到原点上。重点是三个命令
.save()
.translate()//让画笔回原点
.restore()
window.onload=function(){ //下面是刮刮卡的内容 var canvas = document.getElementById("myCanvas"); var pmk = $(window).width(); var pmg = $(document).height(); //$('#myCanvas').attr("width",pmk*0.7); //$('#myCanvas').attr("height","40px"); canvas.width = pmk*0.7; canvas.height = 45; var cxt = canvas.getContext("2d"); var img = new Image(); img.onload = function(){ cxt.drawImage(img,0,0,canvas.width,canvas.height); //cxt.strokeStyle = "rgba(255,255,255,0.1)"; cxt.lineWidth = 20;//线的宽度 cxt.lineCap = "round";//线的两头样式为圆 cxt.lineJoin = "round";//线的拐角样式为圆 cxt.globalCompositeOperation="destination-out";//变透明 cxt.beginPath(); // cxt.moveTo(100,100); // cxt.lineTo(200,200); // cxt.lineTo(100,200); // cxt.stroke(); cxt.save(); cxt.translate(-(pmk*0.15),-(pmg*0.373)); var startX,startY; function touchStart(event){ event.preventDefault(); if(!event.touches.length) return; var touch = event.touches[0]; startX = touch.pageX; startY = touch.pageY; cxt.clearRect(startX,startY,50,50); //cxt.arc(startX,startY,10,0,Math.PI*2,true);画空心圆 cxt.stroke(); cxt.restore(); //cxt.moveTo(100,100); //alert(startX); // cxt.beginPath(); // cxt.clearRect(startX,startY,50,50); // cxt.closePath(); // cxt.fill(); // cxt.restore(); } var closeX,closeY; function touchMove(event){ event.preventDefault(); var touch = event.touches[0]; closeX = touch.pageX; closeY = touch.pageY; console.log(closeX+","+closeY); cxt.lineTo(closeX,closeY); cxt.stroke(); } function touchEnd(event){ event.preventDefault(); //alert(canvas.width); data = cxt.getImageData(0,0,canvas.width,canvas.height).data; console.log(data); for (var i=0,j=0;i<data.length;i+=4){ if(data[i]&&data[i+1]&&data[i+2]&&data[i+3]){ j++; } } //alert(j); //alert(canvas.width*canvas.height*0.5); //假如j的数量小于等于图片的0.7了,就全清除 if(j<=canvas.width*canvas.height*0.7){ cxt.clearRect(0,0,canvas.width,canvas.height); //alert("成功"); //刮刮卡刮完后,可以在这里写回调事件 //刮出终极大奖 //首先判断活动是否开启 if(!getkeyStatus){ //活动尚未开启 $('.fail2,#cover').show(); $('.result').text("活动尚未开启"); return false; } //活动开启后,判断用户的积分是否满5分 if(tadaynums >= 5){ //消除蒙层 $("#myCanvas").hide(); //用户领取成功,将key显示出来,这里默认写了一个key,需要接口提供key $('.success1,#cover').show(); $('.result').text("恭喜你中奖了!"); }else { $('.fail1,#cover').show(); } } } //add touch start listener //canvas.addEventListener("touchstart",touchStart,false); canvas.addEventListener("touchmove",touchMove,false); canvas.addEventListener("touchend",touchEnd,false); }; img.src= "images/canvaspic.png?version="+new Date(); }