如何实现一个,刮刮乐

100 阅读1分钟

juejin222.png

<!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>