近年来因为移动设备对HTML5的较好支持,常常有活动用刮奖的效果,最近也在看H5方面的内容,就本身实现了一个,现分享出来跟你们交流。css
原理很简单,就是在刮奖区添加两个canvas,第一个canvas用于显示刮开后显示的内容,能够是一张图片或一个字符串,第二个canvas用于显示涂层,能够用一张图片或用纯色填充,第二个canvas覆盖在第一个canvas上面。html
当在第二个canvas上点击或涂抹(点击而后拖动鼠标)时,把点击区域变为透明,这样就能够看到第一个canvas上的内容,即实现了刮奖效果。android
function Lottery(id, cover, coverType, width, height, drawPercentCallback) { this.conId = id; this.conNode = document.getElementById(this.conId); this.cover = cover || '#CCC'; this.coverType = coverType || 'color'; this.background = null; this.backCtx = null; this.mask = null; this.maskCtx = null; this.lottery = null; this.lotteryType = 'image'; this.width = width || 300; this.height = height || 100; this.clientRect = null; this.drawPercentCallback = drawPercentCallback; }
对参数解释一下:git
而后还定义了几个须要用到的变量:github
lottery
匹配this.background = this.background || this.createElement('canvas', { style: 'position:absolute;left:0;top:0;' }); this.mask = this.mask || this.createElement('canvas', { style: 'position:absolute;left:0;top:0;' }); if (!this.conNode.innerHTML.replace(/[\w\W]| /g, '')) { this.conNode.appendChild(this.background); this.conNode.appendChild(this.mask); this.clientRect = this.conNode ? this.conNode.getBoundingClientRect() : null; this.bindEvent(); } this.backCtx = this.backCtx || this.background.getContext('2d'); this.maskCtx = this.maskCtx || this.mask.getContext('2d');
这里用于了createElement工具方法,另外还绑定了事件,后面介绍。web
第一个canvas分两种类型,image 和 string,若是是图片直接用canvas的drawImage就能够了,若是是string,要先用白色填充,而后在上下左右居中的地方绘制字符串,代码以下:canvas
if (this.lotteryType == 'image') { var image = new Image(), _this = this; image.onload = function () { _this.width = this.width; _this.height = this.height; _this.resizeCanvas(_this.background, this.width, this.height); _this.backCtx.drawImage(this, 0, 0); } image.src = this.lottery; } else if (this.lotteryType == 'text') { this.width = this.width; this.height = this.height; this.resizeCanvas(this.background, this.width, this.height); this.backCtx.save(); this.backCtx.fillStyle = '#FFF'; this.backCtx.fillRect(0, 0, this.width, this.height); this.backCtx.restore(); this.backCtx.save(); var fontSize = 30; this.backCtx.font = 'Bold ' + fontSize + 'px Arial'; this.backCtx.textAlign = 'center'; this.backCtx.fillStyle = '#F60'; this.backCtx.fillText(this.lottery, this.width / 2, this.height / 2 + fontSize / 2); this.backCtx.restore(); }
第二个canvas也分 image 或 color 填充两种状况。app
这里有一个难点,就是如何把鼠标点击区域变成透明的呢?答案在这里:https://developer.mozilla.org/en/docs/Web/Guide/HTML/Canvas_tutorial/Compositingiphone
即咱们要把 maskCtx的 globalCompositeOperation 设置为 destination-out ,详细的用法请参考上面给出的连接。
ide
所以,绘制第二个canvas的代码以下:
this.resizeCanvas(this.mask, this.width, this.height); if (this.coverType == 'color') { this.maskCtx.fillStyle = this.cover; this.maskCtx.fillRect(0, 0, this.width, this.height); this.maskCtx.globalCompositeOperation = 'destination-out'; } else if (this.coverType == 'image'){ var image = new Image(), _this = this; image.onload = function () { _this.maskCtx.drawImage(this, 0, 0); _this.maskCtx.globalCompositeOperation = 'destination-out'; } image.src = this.cover; }
这里resizeCanvas是改变canvas大小的工具方法。
绘制完成后,要给第二个canvas绑定事件。这里分了移动设备和PC-WEB两处状况。移动设备是 touchstart 和 touchmove 事件,对应的PC-WEB是keydown 和 mousemove事件,另外PC-WEB方式下,要给document绑定一个mouseup事件,用来判断鼠标是否按下。代码以下:
bindEvent: function () { var _this = this; var device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase())); var clickEvtName = device ? 'touchstart' : 'mousedown'; var moveEvtName = device? 'touchmove': 'mousemove'; if (!device) { var isMouseDown = false; document.addEventListener('mouseup', function(e) { isMouseDown = false; }, false); } this.mask.addEventListener(clickEvtName, function (e) { isMouseDown = true; var docEle = document.documentElement; if (!_this.clientRect) { _this.clientRect = { left: 0, top:0 }; } var x = (device ? e.touches[0].clientX : e.clientX) - _this.clientRect.left + docEle.scrollLeft - docEle.clientLeft; var y = (device ? e.touches[0].clientY : e.clientY) - _this.clientRect.top + docEle.scrollTop - docEle.clientTop; _this.drawPoint(x, y); }, false); this.mask.addEventListener(moveEvtName, function (e) { if (!device && !isMouseDown) { return false; } var docEle = document.documentElement; if (!_this.clientRect) { _this.clientRect = { left: 0, top:0 }; } var x = (device ? e.touches[0].clientX : e.clientX) - _this.clientRect.left + docEle.scrollLeft - docEle.clientLeft; var y = (device ? e.touches[0].clientY : e.clientY) - _this.clientRect.top + docEle.scrollTop - docEle.clientTop; _this.drawPoint(x, y); }, false); }
这里在事件中取出了鼠标坐标,调用了drawPoint进行了绘制,下面会讲到。
这里用到了canvas的径向渐变,在鼠标从标处绘制一个圆形,代码以下:
drawPoint: function (x, y) { this.maskCtx.beginPath(); var radgrad = this.maskCtx.createRadialGradient(x, y, 0, x, y, 30); radgrad.addColorStop(0, 'rgba(0,0,0,0.6)'); radgrad.addColorStop(1, 'rgba(255, 255, 255, 0)'); this.maskCtx.fillStyle = radgrad; this.maskCtx.arc(x, y, 30, 0, Math.PI * 2, true); this.maskCtx.fill(); if (this.drawPercentCallback) { this.drawPercentCallback.call(null, this.getTransparentPercent(this.maskCtx, this.width, this.height)); } }
在不少时候,咱们还须要知道用户涂抹了多少而后进行下一步交互,如当用户涂抹了80%后,才容许下一张显示。
这个百分好比何计算呢?其实很简单,咱们能够用getImageData方法到画布上指定矩形的像素数据,因为每一个像素都是用rgba表示的,而涂抹过的区域是透明的,因此咱们只须要判断alpha通道的值就能够知道是否透明。代码以下:
getTransparentPercent: function(ctx, width, height) { var imgData = ctx.getImageData(0, 0, width, height), pixles = imgData.data, transPixs = []; for (var i = 0, j = pixles.length; i < j; i += 4) { var a = pixles[i + 3]; if (a < 128) { transPixs.push(i); } } return (transPixs.length / (pixles.length / 4) * 100).toFixed(2); }
最后再提供一个入口用来进行绘制和重置,代码以下:
init: function (lottery, lotteryType) { this.lottery = lottery; this.lotteryType = lotteryType || 'image'; this.drawLottery(); }
至此,关键代码所有讲解完了。
完整代码及DEMO可看这里:Lottery
欢迎你们留言讨论,若有bug请在github上或本文后面留言。