码迷,mamicode.com
首页 > 移动开发 > 详细

手机刮刮卡

时间:2015-12-23 14:30:26      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!