近年來由於行動裝置對HTML5的較好支持,經常有活動用刮獎的效果,最近也在看H5方面的內容,就自己實現了一個,現分享出來跟大家交流。 #原理很簡單,就是在刮取區增加兩個
canvas,第二個canvas用來顯示塗層,可以用一張圖片或用純色填充,第二個canvas覆蓋在第一個canvas上面。 canvas上點擊或塗抹(點擊然後拖曳滑鼠)時,把點擊區域變成透明,這樣就可以看到第一個canvas上的內容,即實現了刮鬍效果。 (1)定義Lottery類別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;
}
對參數解釋一下:
id:刮獎容器的id
getBoundingClientRect() 值
(2)新增二個canvas到刮獎容器,並取得2d上下文
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');
事件,後面介紹。
,如果是圖片直接用canvas的drawImage就可以了,如果是string,要先用白色填充,然後在上下左右居中的地方繪製字符串,代碼如下:
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(); }(4)繪製第二個canvas
#即我們要把maskCtx的 globalCompositeOperation 設定為 destination-out ,詳細的用法請參考上面給出的連結。
因此,繪製第二個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; }
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進行了繪製,下面會講到。 (6)繪製點擊和塗抹區域這裡用到了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); }(8)呼叫入口init
init: function (lottery, lotteryType) { this.lottery = lottery; this.lotteryType = lotteryType || 'image'; this.drawLottery(); }至此,關鍵程式碼全部講解完了。
以上是HTML5 Canvas實戰之刮獎效果的實例詳情的詳細內容。更多資訊請關注PHP中文網其他相關文章!