HTML5-canvas实例:刮刮乐游戏
生活随笔
收集整理的這篇文章主要介紹了
HTML5-canvas实例:刮刮乐游戏
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
實現方法:
(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>?
轉載于:https://www.cnblogs.com/focuslgy/p/4293534.html
總結
以上是生活随笔為你收集整理的HTML5-canvas实例:刮刮乐游戏的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在Indicator中添加动态Check
- 下一篇: (011) Linux之高级键盘技巧