實現方法:javascript
(1)利用canvas畫布,fillRect()描繪出一個矩形(不是透明),定位蓋在某個標籤如div上面(這個標籤寫着中獎的信息)css
(2)globalCompositeOperation = 'destination-out';利用此屬性,手指劃過畫布,arc(x,y, radius, 0, Math.PI*2, true)繪畫圓形,那麼這個圓形會把以前描繪出的矩形穿透,看到div標籤的內容html
globalCompositeOperation屬性: java
globalCompositeOperation 屬性設置或返回如何將一個源(新的)圖像繪製到目標(已有)的圖像上。canvas
源圖像 = 您打算放置到畫布上的繪圖。this
目標圖像 = 您已經放置在畫布上的繪圖。spa
值 | 描述 |
---|---|
source-over | 默認。在目標圖像上顯示源圖像。 |
source-atop | 在目標圖像頂部顯示源圖像。源圖像位於目標圖像以外的部分是不可見的。 |
source-in | 在目標圖像中顯示源圖像。只有目標圖像內的源圖像部分會顯示,目標圖像是透明的。 |
source-out | 在目標圖像以外顯示源圖像。只會顯示目標圖像以外源圖像部分,目標圖像是透明的。 |
destination-over | 在源圖像上方顯示目標圖像。 |
destination-atop | 在源圖像頂部顯示目標圖像。源圖像以外的目標圖像部分不會被顯示。 |
destination-in | 在源圖像中顯示目標圖像。只有源圖像內的目標圖像部分會被顯示,源圖像是透明的。 |
destination-out | 在源圖像外顯示目標圖像。只有源圖像外的目標圖像部分會被顯示,源圖像是透明的。 |
lighter | 顯示源圖像 + 目標圖像。 |
copy | 顯示源圖像。忽略目標圖像。 |
source-over | 使用異或操做對源圖像與目標圖像進行組合。 |
以下圖,藍色是目標圖像(就是矩形),紅色就是源圖像(即手指劃過的圓形)scala
從圖中能夠看出,globalCompositeOperation = 'destination-out'就是咱們要的屬性code
例子完整代碼:htm
<!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>