標籤:
實現方法:
(1)利用canvas畫布,fillRect()描繪出一個矩形(不是透明),定位蓋在某個標籤如div上面(這個標籤寫著中獎的資訊)
(2)globalCompositeOperation = ‘destination-out‘;利用此屬性,手指划過畫布,arc(x,y, radius, 0, Math.PI*2, true)繪畫圓形,那麼這個圓形會把之前描繪出的矩形穿透,看到div標籤的內容
globalCompositeOperation屬性:
globalCompositeOperation 屬性設定或返回如何將一個源(新的)映像繪製到目標(已有)的映像上。
源映像 = 您打算放置到畫布上的繪圖。
靶心圖表像 = 您已經放置在畫布上的繪圖。
| 值 |
描述 |
| source-over |
預設。在靶心圖表像上顯示源映像。 |
| source-atop |
在靶心圖表像頂部顯示源映像。源映像位於靶心圖表像之外的部分是不可見的。 |
| source-in |
在靶心圖表像中顯示源映像。只有靶心圖表像內的源映像部分會顯示,靶心圖表像是透明的。 |
| source-out |
在靶心圖表像之外顯示源映像。只會顯示靶心圖表像之外源映像部分,靶心圖表像是透明的。 |
| destination-over |
在源映像上方顯示靶心圖表像。 |
| destination-atop |
在源映像頂部顯示靶心圖表像。源映像之外的靶心圖表像部分不會被顯示。 |
| destination-in |
在源映像中顯示靶心圖表像。只有源映像內的靶心圖表像部分會被顯示,源映像是透明的。 |
| destination-out |
在源映像外顯示靶心圖表像。只有源映像外的靶心圖表像部分會被顯示,源映像是透明的。 |
| lighter |
顯示源映像 + 靶心圖表像。 |
| copy |
顯示源映像。忽略靶心圖表像。 |
| source-over |
使用異或操作對源映像與靶心圖表像進行組合。 |
如,藍色是靶心圖表像(就是矩形),紅色就是源映像(即手指划過的圓形)
可以看出,globalCompositeOperation = ‘destination-out‘就是我們要的屬性
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>demo</title> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"/> <style type="text/css"> .wraper{width: 300px;height: 100px;position: relative;margin: 150px auto;} .inner{width: 300px;height: 100px;background: #AA0707;color: #fff;font-size: 36px;line-height: 100px;text-align: center;} #j_canvas{position: absolute;left: 0;top: 0;} </style></head><body> <div class="wraper"> <div class="inner">恭喜您中獎</div> <canvas id="j_canvas" width="300" height="100"></canvas> </div> <script type="text/javascript"> var scratchGame = (function(){ var target = document.getElementById(‘j_canvas‘), ctx = target.getContext(‘2d‘), w = target.width, h = target.height, radius = 15, target_offset_x = target.getBoundingClientRect().left, target_offset_y = target.getBoundingClientRect().top, isTouch = false; return{ init:function(){ ctx.fillStyle = ‘#999‘; ctx.fillRect(0, 0,w,h); //屬性設定或返回如何將一個源(新的)映像繪製到目標(已有)的映像上。 ctx.globalCompositeOperation = ‘destination-out‘; // 事件 target.addEventListener(‘touchstart‘, this.eventDown,false); target.addEventListener(‘touchmove‘, this.eventMove,false); target.addEventListener(‘touchend‘, this.eventUp,false); }, eventDown:function(e){ e.preventDefault(); isTouch = true; }, eventUp:function(e){ e.preventDefault(); isTouch = false; }, eventMove:function(e){ e.preventDefault(); if(!isTouch||!e.touches.length) return; var touch = e.touches[0], x = touch.pageX - target_offset_x, y = touch.pageY - target_offset_y; ctx.beginPath(); ctx.arc(x,y, radius, 0, Math.PI*2, true); ctx.fill(); } } })(); scratchGame.init(); </script></body></html>
HTML5-canvas執行個體:刮刮樂遊戲