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

电脑杂谈  发布时间:2019-09-03 15:07:46  来源:网络整理

html5 canvas 刮刮乐_html5 canvas 游戏开发_html5 canvas 刮刮乐

var canvas = document.getElementById('myCanvas'),
    ctx = canvas.getContext('2d'),
    w = canvas.width;
    h = canvas.height;
    area = w * h;
    l = canvas.offsetLeft;
    t = canvas.offsetTop,
    img = new Image();

获取canvas对象或者它的上下文对象

area变量是为以下的像素点测试所准备

img用来进行截图预加载

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

var init = (function(){
    ctx.fillStyle = "#ccc";
    ctx.fillRect(0, 0, w, h);
    randomImg();            
    img.addEventListener('load', function(){
        canvas.style.backgroundImage = 'url(' + img.src +')';
        ctx.globalCompositeOperation = 'destination-out';
        bindEvent();
    });
})();

html5 canvas 游戏开发_html5 canvas 刮刮乐_html5 canvas 刮刮乐

流程如下:

将整个canvas覆盖蓝层

随机图片

图片预加载

加载完毕后html5 canvas 刮刮乐,设置截图为canvas背景

刮卡前,设置ctx.globalCompositeOperation = 'destination-out';

html5 canvas 刮刮乐_html5 canvas 刮刮乐_html5 canvas 游戏开发

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

randomImg函数的功能就是随机图片

随机图片就应该利用Math.random()随机数

canvas我们应该绑定两个函数

html5 canvas 刮刮乐_html5 canvas 刮刮乐_html5 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();
};

滑动屏幕就要画一个圆

由于设置了destination-out ,所以造成了刮卡的效果

还要切记html5 canvas 刮刮乐,每次触发都要ctx.beginPath();

否则ctx.fill();会连接之前划过的圆,大面积刮涂

html5 canvas 刮刮乐_html5 canvas 游戏开发_html5 canvas 刮刮乐

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

手抬起时,就会触发touchend

在这个函数中,我们运用了ctx.getImageData()获取了canvas的像素信息

关于这个函数的用法可以戳这里

当红层被刮开后,后面就是canvas的背景

所以我们可以借助判断像素信息RGBA中的A是否为0来判定图层是否被刮开

scrapeNum就代表被刮开的像素点

所以通过scrapeNum > area * 0.7的判断

当刮开的范围小于总范围的70%时

清除整个灰色图层


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/ruanjian/article-121571-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      • 廖煜东
        廖煜东

        12海里领海和200海里专属经济区规定的既定事实

      热点图片
      拼命载入中...