>  기사  >  웹 프론트엔드  >  모바일 터치 이벤트 및 H5-Canvas 픽셀 감지로 스크래치 오프 실현

모바일 터치 이벤트 및 H5-Canvas 픽셀 감지로 스크래치 오프 실현

黄舟
黄舟원래의
2017-02-27 15:28:062174검색


요즘 알리페이 지푸 캐릭터에 푹 빠졌어요
아직 헌신의 축복(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>

아래에 간략하게 설명하겠습니다
우선 페이지에서는 캔버스 요소만 필요합니다

<canvas id="myCanvas" width=300 height=300></canvas>

CSS에서는 캔버스 배경 이미지의 스타일을 미리 설정해야 합니다

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

스크립트에서 먼저 필수 변수를 선언해야 합니다

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

캔버스 개체 및 해당 컨텍스트 개체 가져오기
다음 픽셀 감지를 위해 영역 변수가 준비됩니다
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();
    });
})();

프로세스는 다음과 같습니다.

  • 캔버스 전체를 회색 레이어

  • 임의의 사진

  • 이미지 사전 로드

  • 로드 후 이미지를 다음과 같이 설정합니다. 캔버스 배경

  • 스크래치하기 전에 ctx.globalCompositeOperation = 'destination-out';

  • 캔버스, Tuka에 대한 청취 이벤트 바인딩

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

randomImg 기능의 기능은 사진을 무작위로 만드는 것입니다
무작위로 그림을 보려면 Math.random() 난수를 사용해야 합니다


캔버스에서 두 함수를 바인딩해야 합니다
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();};

화면을 슬라이드하려면 원을 그려야 합니다
destination-out 설정으로 인해 스크래치 효과가 발생합니다
또한 각 트리거는 ctx.beginPath();
이어야 합니다. 그렇지 않으면 ctx.fill();는 이전에 그린 원을 연결하고 넓은 영역을 긁습니다.

rree

손을 올리면 터치엔드가 실행됩니다.
이 함수에서는 ctx.getImageData()을 사용하여 Pixel을 얻습니다. 캔버스 정보
이 기능을 사용하려면 여기를 클릭하세요
회색 레이어가 긁히면 캔버스의 배경이 뒤에 있습니다
픽셀 정보의 RGBA에서 A가 있는지 판단할 수 있습니다 0입니다. 레이어가 긁혔는지 확인
scrapeNum은 긁힌 픽셀을 나타냅니다
따라서 scrapeNum > area * 0.7으로 판단합니다
긁힌 범위가 전체 범위의 70%보다 큰 경우
클리어 전체 회색 레이어

위 내용은 스크래치 오프를 구현하기 위한 모바일 Touch 이벤트 및 H5-Canvas 픽셀 감지 내용입니다. 자세한 내용은 PHP 중국어 웹사이트(www.php.cn)를 참고하세요. )!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.