
实现方法:
(1)利用canvas画布,fillRect()描绘出一个矩形(不是透明),定位盖在某个标签如div上面(这个标签写着中奖的信息)
(2)globalCompositeOperation = 'destination-out';利用此属性,手指划过画布,arc(x,y, radius, 0, Math.PI*2, true)绘画圆形,那么这个圆形会把之前描绘出的矩形穿透,看到div标签的内容
globalCompositeOperation属性:
globalCompositeOperation 属性设置或返回如何将一个源(新的)图像绘制到目标(已有)的图像上。
源图像 = 您打算放置到画布上的绘图。
目标图像 = 您已经放置在画布上的绘图。
如下图,蓝色是目标图像(就是矩形),红色就是源图像(即手指划过的圆形)
?
从图中可以看出,globalCompositeOperation = 'destination-out'就是我们要的属性
例子完整代码:
? ? 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();
? ?