Maison > interface Web > Tutoriel H5 > le corps du texte

移动端Touch事件与H5-Canvas像素点检测实现刮刮乐

黄舟
Libérer: 2017-02-27 15:28:06
original
2188 Les gens l'ont consulté


最近又被支付宝的集福字刷屏了
我到底还是没看到敬业福ค(TㅅT) 心塞
今天给大家带来移动端的刮刮乐实现
效果就是这样的

手滑动触发刮卡

当刮卡面积达到70%以上,自动刮开全部灰色图层


代码不是很多
全部代码就这些

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta content="width=device-width,maximum-scale=1.0,minimum-scale=1.0,initial-scale=1.0,user-scalable=no" name="viewport">
    <title>Scrape</title>
    <style>
        #myCanvas {            
        background-repeat: no-repeat;            
        background-position: center;            
        background-size: 200px 200px;        
        }
    </style></head><body>
    <canvas id="myCanvas" width=300 height=300></canvas>
    <script>
        var canvas = document.getElementById(&#39;myCanvas&#39;),
            ctx = canvas.getContext(&#39;2d&#39;),
            w = canvas.width;
            h = canvas.height;
            area = w * h;
            l = canvas.offsetLeft;
            t = canvas.offsetTop,
            img = new Image();        
            var randomImg = function(){
            var random = Math.random();            
            if(random < 0.4){
                img.src = &#39;./1.png&#39;;
            }else if(random > 0.6){
                img.src = &#39;./2.png&#39;;
            }else{
                img.src = &#39;./award.jpg&#39;;
            }
        };        var bindEvent = function(){
            canvas.addEventListener(&#39;touchmove&#39;, moveFunc, false);
            canvas.addEventListener(&#39;touchend&#39;, endFunc, false);
        };        var moveFunc = function(e){
            var touch = e.touches[0],
                posX = touch.clientX - l,
                posY = touch.clientY - t;
            ctx.beginPath();
            ctx.arc(posX, posY, 15, 0, Math.PI * 2, 0);
            ctx.fill();
        };        var endFunc = function(e){
            var data = ctx.getImageData(0, 0, w, h).data,
                scrapeNum = 0;            
                for(var i = 3, len = data.length; i < len; i += 4){                
                if(data[i] === 0){
                    scrapeNum++;
                }
            }            if(scrapeNum > area * 0.7){
                ctx.clearRect(0, 0, w, h);
                canvas.removeEventListener(&#39;touchmove&#39;, moveFunc, false);
                canvas.removeEventListener(&#39;touchend&#39;, endFunc, false);
            }
        }        var init = (function(){
            ctx.fillStyle = "#ccc";
            ctx.fillRect(0, 0, w, h);
            randomImg();            
            img.addEventListener(&#39;load&#39;, function(){
                canvas.style.backgroundImage = &#39;url(&#39; + img.src +&#39;)&#39;;
                ctx.globalCompositeOperation = &#39;destination-out&#39;;
                bindEvent();
            });
        })();    </script></body></html>
Copier après la connexion

下面我就简单说明一下
首先在页面中我们只需要一个canvas元素

<canvas id="myCanvas" width=300 height=300></canvas>
Copier après la connexion

CSS中的我们需要对canvas的背景图片事先设置好样式

#myCanvas {    
background-repeat: no-repeat;    
background-position: center;    
background-size: 200px 200px;}
Copier après la connexion

脚本中我们首先要声明所需变量

var canvas = document.getElementById(&#39;myCanvas&#39;),
    ctx = canvas.getContext(&#39;2d&#39;),
    w = canvas.width;
    h = canvas.height;
    area = w * h;
    l = canvas.offsetLeft;
    t = canvas.offsetTop,
    img = new Image();
Copier après la connexion

获取canvas对象以及它的上下文对象
area变量是为下面的像素点检测所准备
img用来进行图片预加载


最关键的函数在于init初始化函数

var init = (function(){
    ctx.fillStyle = "#ccc";
    ctx.fillRect(0, 0, w, h);
    randomImg();            
    img.addEventListener(&#39;load&#39;, function(){
        canvas.style.backgroundImage = &#39;url(&#39; + img.src +&#39;)&#39;;
        ctx.globalCompositeOperation = &#39;destination-out&#39;;
        bindEvent();
    });
})();
Copier après la connexion

流程如下:

  • 将整个canvas覆盖灰色图层

  • 随机图片

  • 图片预加载

  • 加载完毕后,设置图片为canvas背景

  • 刮卡前,设置ctx.globalCompositeOperation = &#39;destination-out&#39;;

  • 为canvas绑定监听事件,涂卡

这个globalCompositeOperation才是刮刮乐的关键
关于这个属性的用法可以戳这里


var randomImg = function(){
    var random = Math.random();    if(random < 0.4){
        img.src = &#39;./1.png&#39;;
    }else if(random > 0.6){
        img.src = &#39;./2.png&#39;;
    }else{
        img.src = &#39;./award.jpg&#39;;
    }
};
Copier après la connexion

randomImg函数的功能就是随机图片
随机图片就需要利用Math.random()随机数


canvas我们需要绑定两个函数
touchmove和touchend

var moveFunc = function(e){
    var touch = e.touches[0],
        posX = touch.clientX - l,
        posY = touch.clientY - t;
    ctx.beginPath();
    ctx.arc(posX, posY, 15, 0, Math.PI * 2, 0);
    ctx.fill();};
Copier après la connexion

滑动屏幕就要画一个圆
由于设置了destination-out ,所以产生了刮卡的效果
还要注意,每次触发都要ctx.beginPath();
否则ctx.fill();会连接之前划过的圆,大面积刮涂

var endFunc = function(e){
    var data = ctx.getImageData(0, 0, w, h).data,
        scrapeNum = 0;    
        for(var i = 3, len = data.length; i < len; i += 4){        
        if(data[i] === 0){
            scrapeNum++;
        }
    }    if(scrapeNum > area * 0.7){
        ctx.clearRect(0, 0, w, h);
        canvas.removeEventListener(&#39;touchmove&#39;, moveFunc, false);
        canvas.removeEventListener(&#39;touchend&#39;, endFunc, false);
    }
}
Copier après la connexion

手抬起时,就会触发touchend
在这个函数中,我们利用了ctx.getImageData()获取了canvas的像素信息
关于这个函数的用法可以戳这里
当灰色图层被刮开后,后面就是canvas的背景
所以我们可以通过判断像素信息RGBA中的A是否为0来判断图层是否被刮开
scrapeNum就代表被刮开的像素点  
所以通过scrapeNum > area * 0.7的判断
当刮开的范围大于总范围的70%时
清除整个灰色图层

 以上就是移动端Touch事件与H5-Canvas像素点检测实现刮刮乐的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!