添加鼠标按下并移动事件的解决方案
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> 刮刮乐 </title>
<style type="text/css">
div {
border: 1px solid #000;
width: 250px;
height: 100px;
text-align: center;
line-height: 100px;
font-size: 40px;
font-weight: bold;
user-select: none;
position: relative;
}
canvas {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div>
特等奖
<canvas width="250" height="100">
当前浏览器版本不支持, 请更新浏览器
</canvas>
</div>
<script type="text/javascript">
var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#ccc";
ctx.fillRect(0, 0, canvas.width, canvas.height);
mouseDownAndMove(canvas, function(even) {
ctx.globalCompositeOperation = "destination-out";
ctx.beginPath();
ctx.arc(even.offsetX, even.offsetY, 10, 0, 2 * Math.PI, false);
ctx.fill();
});
function mouseDownAndMove(dom, callback) {
let flag = false;
let fn = function(e) {
if (i) callback(e);
};
dom.addEventListener("mousedown", function(even) {
flag = true;
dom.addEventListener("mousemove", fn)
})
dom.addEventListener("mouseup", function() {
i = false;
dom.removeEventListener("mousemove", fn);
})
document.addEventListener("mouseup", function() {
flag = false;
dom.removeEventListener("mousemove", fn);
});
}
</script>
</body>
</html>