search
HomeWeb Front-endH5 TutorialMobile Touch event and H5-Canvas pixel detection to realize scratch-off


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>

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>

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;}

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();

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

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;;
    }
};

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

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);
    }
}

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 (www.php.cn)!


Statement
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
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools