<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>高级刮刮乐</title>
<styletype="text/css">
#cont{
border:1px solid red;
}
img{
width:500px;
height:500px;
position:absolute;
z-index:-1;
}
</style>
</head>
<body>
<imgsrc="img/美女.jpg"/>
<canvasid="cont"width="500"height="500"></canvas>
</body>
<scripttype="text/javascript">
varmyCanvas = document.getElementById("cont");
var txt = myCanvas.getContext("2d");
//添加蒙版
txt.fillStyle= "darkgray";
txt.fillRect(0,0, myCanvas.width, myCanvas.height);
//鼠标事件
myCanvas.onclick= function() {
//鼠标移动
document.onmousemove= function(event) {
//获取鼠标的位置
varpointX = event.clientX- myCanvas.offsetLeft;
var pointY= event.clientY- myCanvas.offsetTop;
//设置蒙版和圆的组合方式,只保留原图未处理部分.
txt.globalCompositeOperation= "destination-out"
//画圆
txt.beginPath();
txt.arc(pointX, pointY, 20, 0, Math.PI * 2, false);
txt.closePath();
txt.fillStyle = "white";
txt.fill();
//判断抹掉一半,整体消失
adjust();
}
//点击松开
document.onmouseup= function() {
document.onmousemove= null;
}
//判断像素点
function adjust(){
//获取像素点数组
varpxarr = txt.getImageData(0,0,myCanvas.width,myCanvas.height).data;
//一个像素点存储4个值,rgba值
varcount = 0;//定义一个记录透明度为0的像素点的个
for(vari =0;i<pxarr.length;i+=4){
//当抹掉的时候,一个像素点的a值是0;
if(pxarr[i+3]== 0){
count++;
}
}
console.log(count);
//如果累加到所有像素点一半时,清除整个蒙版
//pxarr.length/4总是像素点个数
if(count>=pxarr.length/8){
txt.clearRect(0,0,myCanvas.width,myCanvas.height)
}
}
}
</script>
</html>