标签:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, width=device-width,minimum-scale=1.0,maximum-scale=1.0, user-scalable=no" /> <title> 刮刮卡 </title> </head> <body> <canvas id="canvas" width="300" height="150"></canvas> <script> var oCanvas = document.getElementById(‘canvas‘), aPrizeList = [‘images/1.jpg‘, ‘images/2.jpg‘],//控制中奖几率 prizeImg = aPrizeList[Math.floor(Math.random() * aPrizeList.length)]; scratch(oCanvas, prizeImg, 0.3, function(){ alert(‘成功!‘); }); /** * 刮刮卡 * @param oCanvas canvas绘图对象 * @param prizeImg 中奖图片 * @param scale 刮开区域占比 * @param callback 刮开后执行的函数 */ function scratch(oCanvas, prizeImg, scale, callback){ if(!oCanvas.getContext) return; var w = oCanvas.getAttribute(‘width‘), h = oCanvas.getAttribute(‘height‘), ctx = oCanvas.getContext(‘2d‘), fn = callback || function(){}, bEnd = false; // 防止touchend多次执行回调 // 设置奖品图片 oCanvas.style.background = ‘url(‘+ prizeImg +‘) 0 0/cover no-repeat‘; // 绘制灰色刮奖区域 ctx.fillStyle = "#999"; ctx.fillRect(0,0, w, h); // 设置重叠显示方式 ctx.globalCompositeOperation="destination-out"; // 绑定事件 oCanvas.addEventListener(‘touchstart‘, function(){ // 按下并滑动 oCanvas.addEventListener(‘touchmove‘, function(e){ e.preventDefault(); var x = e.targetTouches[0].clientX + document.body.scrollLeft - oCanvas.offsetLeft, y = e.targetTouches[0].clientY + document.body.scrollTop - oCanvas.offsetTop; ctx.beginPath(); ctx.arc(x, y, 15, 0, Math.PI*2); ctx.fill(); ctx.closePath(); }); oCanvas.addEventListener(‘touchend‘, function(e){ e.preventDefault(); var count = 0, datas = ctx.getImageData(0,0,w,h); for (var i = 0, len = datas.data.length; i < len; i++) { if (datas.data[i] == 0) { count++; } } if (count >= datas.data.length * scale && !bEnd) { fn(); ctx.fillRect(0,0,w,h); bEnd = true; } }); }); } </script> </body> </html>
效果如图:
标签:
原文地址:http://www.cnblogs.com/beiz/p/5069682.html