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
- 下一篇: HTML big 标签