
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>刮刮卡效果</title>
</head>
<style>
body {
margin: 0;
}
#canvas {
position: absolute;
left: 0;
cursor: pointer;
}
</style>
<img id="image" src="https://p3-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/f1165133464843f091833b107f213b80~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgd2ViX19f:q75.awebp?rk3s=f64ab15b&x-expires=1771050502&x-signature=mSE44LxkUckb%2Fbiji5paLgrpbIA%3D">
<canvas id="canvas"></canvas>
</html>
<script>
function draw() {
var canvas = document.getElementById('canvas');
var img = document.getElementById('image');
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
if (!canvas.getContext) return;
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.fillStyle = "gray";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = 'destination-out';
ctx.lineCap = 'round';
ctx.lineWidth = 100;
canvas.onmousedown = function(e) {
console.log("按下");
var x = e.offsetX;
var y = e.offsetY;
ctx.moveTo(x, y);
moves();
}
function moves() {
canvas.onmousemove = function(e) {
console.log("移动");
var x = e.offsetX;
var y = e.offsetY;
ctx.lineTo(x, y);
ctx.stroke();
}
}
canvas.onmouseup = function(e) {
console.log("抬起");
canvas.onmousemove = null;
}
}
}
draw();
</script>