最近有人在论坛里提问,如何实现H5的刮刮卡功能?我之前做过两个demo,源码上传在csdn:demo
我就特意整理写了这篇文章来实现刮刮卡的功能。因为刮刮卡的功能在生活中太常见了,比如我们上手机淘宝,蚂蚁花呗,淘宝淘金币刮刮卡,360手机登录后的刮奖等等都有刮刮卡的功能,所以我觉得它是有很大的价值的!先看下运行的效果:
我们分析下设计思路:
1.刮刮卡的灰色可刮区域,我们用canvas实现
2.刮刮卡的滑动事件我们采用touchstart,touchend,touchmove,mousedown,mouseup,mousemove
3.刮刮卡的滑块划过的区域变为透明
4.刮刮卡整体90%的灰色刮掉算刮完成了
全部代码如下:
<!DOCTYPE html> <html> <body> <meta name="viewport" content="width=device-width,initial-scale=1"> <!-- :www.xttblog.com --> <canvas id="xttblog"></canvas> <script> (function(bodyStyle) { bodyStyle.mozUserSelect = 'none'; bodyStyle.webkitUserSelect = 'none'; var img = new Image(); var canvas = document.querySelector('canvas'); canvas.style.backgroundColor='transparent'; canvas.style.position = 'absolute'; img.addEventListener('load', function(e) { var ctx; var w = img.width, h = img.height; var offsetX = canvas.offsetLeft, offsetY = canvas.offsetTop; var mousedown = false; function layer(ctx) { ctx.fillStyle = 'gray'; ctx.fillRect(0, 0, w, h); } function eventDown(e){ e.preventDefault(); mousedown=true; } function eventUp(e){ e.preventDefault(); mousedown=false; } function eventMove(e){ e.preventDefault(); if(mousedown) { if(e.changedTouches){ e=e.changedTouches[e.changedTouches.length-1]; } var x = (e.clientX + document.body.scrollLeft || e.pageX) - offsetX || 0, y = (e.clientY + document.body.scrollTop || e.pageY) - offsetY || 0; with(ctx) { beginPath() arc(x, y, 5, 0, Math.PI * 2); fill(); } } } canvas.width=w; canvas.height=h; canvas.style.backgroundImage='url('+img.src+')'; ctx=canvas.getContext('2d'); ctx.fillStyle='transparent'; ctx.fillRect(0, 0, w, h); layer(ctx); ctx.globalCompositeOperation = 'destination-out'; canvas.addEventListener('touchstart', eventDown); canvas.addEventListener('touchend', eventUp); canvas.addEventListener('touchmove', eventMove); canvas.addEventListener('mousedown', eventDown); canvas.addEventListener('mouseup', eventUp); canvas.addEventListener('mousemove', eventMove); }); img.src = 'http://sandbox.runjs.cn/uploads/rs/133/80kwuubo/574.png'; })(document.body.style); </script> </body> </html>
点击此处查看运行效果
版权声明:本文为博主原创文章,未经博主允许不得转载。
: » HTML5实现移动设备的淘宝淘金币刮刮卡功能
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/251150.html