<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>刮刮卡</title>
<style type="text/css">
.card{
width: 500px;
height: 300px;
background-image: url(img/earth.png);
/* 背景图片 */
}
</style>
</head>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<body>
<div class="card">
<canvas id="hyy" width="500" height="300">你的浏览器不支持 canvas,请升级你的浏览器</canvas>
</div>
</body>
<script type="text/javascript">
var c=document.getElementById('hyy');
var ctx=c.getContext('2d');
ctx.fillStyle='darkgrey';//灰色
ctx.fillRect(0,0,500,300);
$(document).mousemove(function(event){//鼠标移动监听
ctx.globalCompositeOperation='destination-out';//只显示旧图像没有与新图像重叠的部分
ctx.beginPath();
ctx.arc(event.pageX,event.pageY,20,0, 2 * Math.PI);//当前鼠标为中心画圆
ctx.fill();
var imgData=ctx.getImageData(0,0,500,300);//获取像素信息
var cout=0;
for (var i = 0; i < imgData.data.length; i++) {
if(imgData.data[i]=="0"){//如果擦除的地方像素值为0
cout++;
}
if(cout>imgData.data.length*0.8){//如果擦除面积>80%就全部显示
ctx.clearRect(0,0,500,300);
$.fn.moveStopEvent = function(callback){};//停止鼠标移动监听
break;
}
}
});
</script>
</html>
主要通过
ctx.globalCompositeOperation=‘destination-out’;//只显示旧图像没有与新图像重叠的部分
实现刮刮卡效果
由此启发,以后要擦除canvas中的一些圆形区域也可以通过设置ctx.globalCompositeOperation值的变换来实现,不需要再像魔法阵里面一样写个函数用clearRect一点一点擦除了TAT