canvas刮奖

Posted super-scarlett

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了canvas刮奖相关的知识,希望对你有一定的参考价值。

(function (global, factory) {

typeof module === ‘object‘ && typeof module.exports === ‘object‘ ? module.exports = factory() :

typeof define === ‘function‘ && define.amd ? define(factory) :

global.cavns = factory(global);

})(this, function () {

var cavns = {

position:{

oLeft:"",

oTop:""

},

ctx:"",

init : function(n){

var pic = new Image();

//pic.src ="images/lottery/lottery.png";

var src = document.getElementById("lotpng").src;

pic.src = src;

pic.onload = function(){

var canvas = document.getElementById("canvas");

cavns.ctx = canvas.getContext("2d");

cavns.ctx.beginPath();

cavns.ctx.drawImage(pic,0,0,300,180);

/*this.ctx.fillStyle = ‘rgba(0,0,0, 0.5)‘*/;

/*this.ctx.fillRect(0, 0, canvas.width, canvas.height);*/

cavns.ctx.closePath();

var arr = cavns.getOffset(canvas);

cavns.position.oLeft = arr[0];

cavns.position.oTop = arr[1];

}

},

getOffset:function(obj){

var valLeft = 0,valTop = 0;

function get(obj){

valLeft += obj.offsetLeft;

valTop += obj.offsetTop;

/* 不到最外层就一直调用,直到offsetParent为body*/

if (obj.offsetParent.tagName!=‘BODY‘) {

get(obj.offsetParent);

}

return [valLeft,valTop];

}

return get(obj);

},

touchstart : function(){

this.ctx.beginPath();

this.ctx.lineWidth = 25;

this.ctx.globalCompositeOperation = ‘destination-out‘;

this.ctx.moveTo(event.touches[0].pageX-cavns.position.oLeft, event.touches[0].pageY-cavns.position.oTop);

},

touchmove : function(){

/* 根据手指移动画线,使之变透明*/

this.ctx.lineTo(event.touches[0].pageX-cavns.position.oLeft, event.touches[0].pageY-cavns.position.oTop);

/* 填充*/

this.ctx.stroke();

},

touchend : function(fn){

/* 获取imageData对象*/

var imageDate = this.ctx.getImageData(0, 0, canvas.width, canvas.height);

/* */

var allPX = imageDate.width * imageDate.height;

 

var iNum = 0; //记录刮开的像素点个数

 

for (var i = 0; i < allPX; i++) {

if (imageDate.data[i * 4 + 3] == 0) {

iNum++;

}

}

if (iNum >= allPX * 1 / 20) {

typeof fn == ‘function‘ && fn();

}

}

}

return cavns;

});

以上是关于canvas刮奖的主要内容,如果未能解决你的问题,请参考以下文章

canvas文本自动换行

svg好还是canvas好

第513期Canvas 最佳实践(性能篇)

Android刮奖效果

Android刮奖效果

Andriod实现刮刮卡的效果