这个刮刮卡PC端和移动端都可以用使用
首发的公众号[小白讲前端]欢迎大家关注浏览
PC端展现

移动端展示


源码(PC和移动端直接复制运行)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>刮刮卡效果</title>
</head>
<style>
body {
margin: 0;
background-color: pink;
}
#canvas {
position: absolute;
left: 0;
cursor: pointer;
}
h1{
text-align: center;
}
</style>
<body>
<div
style="position: relative; width: 700px;height: 300px;background-color: red; display: flex; justify-content: space-between; align-items: center;">
<h1>关注小白讲前端</h1>
<canvas id="canvas" width="700" height="300"> </canvas>
</div>
</body>
</html>
<script>
function draw() {
var canvas = document.getElementById('canvas');
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 = 40;
function start(e) {
e.preventDefault();
var x = e.clientX || e.touches[0].clientX;
var y = e.clientY || e.touches[0].clientY;
ctx.moveTo(x, y);
move();
}
function move() {
canvas.addEventListener('mousemove', drawLine);
canvas.addEventListener('touchmove', drawLine);
}
function drawLine(e) {
e.preventDefault();
var x = e.clientX || e.touches[0].clientX;
var y = e.clientY || e.touches[0].clientY;
ctx.lineTo(x, y);
ctx.stroke();
}
function end(e) {
e.preventDefault();
canvas.removeEventListener('mousemove', drawLine);
canvas.removeEventListener('touchmove', drawLine);
}
canvas.addEventListener('mousedown', start);
canvas.addEventListener('touchstart', start);
canvas.addEventListener('mouseup', end);
canvas.addEventListener('touchend', end);
}
draw();
</script>