Last active
August 29, 2015 14:02
-
-
Save weishai/35771888fa29a0c2a441 to your computer and use it in GitHub Desktop.
Html5 Canvas 实现的可刮涂层效果
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
e.preventDefault(); | |
mousedown = false; | |
var data=ctx.getImageData(0,0,w,h).data; | |
for(var i=0,j=0;i< data.length;i+=4){ | |
if(data[i] && data[i+1] && data[i+2] && data[i+3]){ | |
j++; | |
} | |
} | |
if(j<=w*h*0.1){ | |
alert('ok'); | |
} | |
//这段代码中的0.1是10%的意思,在涂层的面积小于等于10%时,就弹出窗口,表示刮完了 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(bodyStyle) { | |
bodyStyle.mozUserSelect = 'none'; | |
bodyStyle.webkitUserSelect = 'none'; | |
var img = new Image(); | |
var canvas = document.querySelector('canvas'); | |
canvas.style.backgroundColor='transparent'; | |
canvas.style.position = 'absolute'; | |
img.addEventListener('load', function(e) { | |
var ctx; | |
var w = img.width, | |
h = img.height; | |
var offsetX = canvas.offsetLeft, | |
offsetY = canvas.offsetTop; | |
var mousedown = false; | |
function layer(ctx) { | |
ctx.fillStyle = 'gray'; | |
ctx.fillRect(0, 0, w, h); | |
} | |
function eventDown(e){ | |
e.preventDefault(); | |
mousedown=true; | |
} | |
function eventUp(e){ | |
e.preventDefault(); | |
mousedown=false; | |
} | |
function eventMove(e){ | |
e.preventDefault(); | |
if(mousedown) { | |
if(e.changedTouches){ | |
e=e.changedTouches[e.changedTouches.length-1]; | |
} | |
var x = (e.clientX + document.body.scrollLeft || e.pageX) - offsetX || 0, | |
y = (e.clientY + document.body.scrollTop || e.pageY) - offsetY || 0; | |
with(ctx) { | |
beginPath() | |
arc(x, y, 5, 0, Math.PI * 2); | |
fill(); | |
} | |
} | |
} | |
canvas.width=w; | |
canvas.height=h; | |
canvas.style.backgroundImage='url('+img.src+')'; | |
ctx=canvas.getContext('2d'); | |
ctx.fillStyle='transparent'; | |
ctx.fillRect(0, 0, w, h); | |
layer(ctx); | |
ctx.globalCompositeOperation = 'destination-out'; | |
canvas.addEventListener('touchstart', eventDown); | |
canvas.addEventListener('touchend', eventUp); | |
canvas.addEventListener('touchmove', eventMove); | |
canvas.addEventListener('mousedown', eventDown); | |
canvas.addEventListener('mouseup', eventUp); | |
canvas.addEventListener('mousemove', eventMove); | |
}); | |
img.src =''; | |
})(document.body.style); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment