1、主要使用clearRect来实现清除表层内容
2、在按下事件里边嵌套移动事件,将当前鼠标距离所在盒子水平距离和垂直方向距离分别作为clearRect的第一个和第二个参数。
直接上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>刮刮乐</title>
<style>
.box{
margin:0 auto;
text-align: center;
}
#canvas{
border:1px solid;
z-index: 2;
}
.endState{
color:red;
width: 500px;
height: 200px;
background: orange;
}
.endState h2{
color:purple;
line-height: 200px;
}
.main{
width: 500px;
height: 200px;
position: relative;
margin:0 auto;
}
.main canvas,.main div{
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="box">
<h2>欢迎刮奖</h2>
<div class="main">
<canvas width="500" height="200" id='canvas'></canvas>
<div class="endState"><h2>恭喜您喜中一等奖</h2></div>
</div>
</div>
<script>
window.onload=function(){
let canvas=document.getElementById('canvas');
let ctx=canvas.getContext('2d');
ctx.strokeStyle='blue';
ctx.beginPath();
ctx.moveTo(0,0);
ctx.rect(0,0,600,300);
ctx.fillStyle='#eee';
ctx.fill();
canvas.onmousedown=function(){
canvas.onmousemove=function(e){
ctx.clearRect(e.offsetX,e.offsetY,16,16);
}
document.onmouseup=function(){
canvas.onmousemove=null;
document.onmousedown=null;
}
}
}
</script>
</body>
</html>
效果图: