Home > Web Front-end > H5 Tutorial > body text

Mobile Touch event and H5-Canvas pixel detection to realize scratch-off

黄舟
Release: 2017-02-27 15:28:06
Original
2187 people have browsed it


Recently I have been flooded with Alipay’s Jifu character
I still haven’t seen Jingyefuค(TㅅT) and I’m heartbroken
I’ll bring it to you today The
effect of the scratch card on the mobile terminal is like this

Swipe your hand to trigger the scratch card

When the scratch card area reaches more than 70%, all gray layers will be automatically scratched


Not a lot of code
That’s all the code

<!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>
Copy after login

Let me explain it briefly
First of all, in the page we only We need a canvas element

<canvas id="myCanvas" width=300 height=300></canvas>
Copy after login

In CSS we need to set the style of the canvas background image in advance

#myCanvas {    
background-repeat: no-repeat;    
background-position: center;    
background-size: 200px 200px;}
Copy after login

In the script we first need to declare the required variables

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();
Copy after login

Get the canvas object and its context object
area variable is prepared for the following pixel detection
img is used for image preloading


The most critical function is the init initialization function

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();
    });
})();
Copy after login

The process is as follows:

  • Cover the entire canvas with the gray layer

  • Random pictures

  • Picture preloading

  • After loading, set the picture as canvas background

  • Before scratching the card, set ctx .globalCompositeOperation = 'destination-out';

  • #Bind listening events for canvas, Tuca

This globalCompositeOperation is the scratch-off The key
For the usage of this attribute, you can click here


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;;
    }
};
Copy after login

The function of the randomImg function is to randomize pictures
For random pictures, you need to use Math.random() random numbers


canvas we need to bind two functions
touchmove and 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();};
Copy after login

To draw a circle when sliding the screen
Because destination-out is set, a scratch effect occurs
Also note that every time it is triggered All mustctx.beginPath();
Otherwisectx.fill();will connect the previously drawn circles and scrape over a large area

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);
    }
}
Copy after login

When lifted, touchend will be triggered
In this function, we used ctx.getImageData() to obtain the pixel information of the canvas
For the usage of this function, you can click here
When the gray layer is scratched, the background of the canvas is behind it
So we can judge whether the layer has been scratched by judging whether A in the pixel information RGBA is 0
scrapeNum represents the scraped pixel Click
So by scrapeNum > area * 0.7
When the scraped range is greater than 70% of the total range
Clear the entire gray layer

and above It is the content of mobile touch event and H5-Canvas pixel detection to realize scratch-off. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!