鼠标按下并移动事件的解决方案

添加鼠标按下并移动事件的解决方案

<!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();
        });


        /**
         * 鼠标按下并移动事件
         * dom : 待绑定的dom 元素
         * callback: 鼠标按下并移动时 需要执行的函数
         */
        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);
            })
			// 当鼠标在其他元素中弹起时的操作, 规避鼠标弹起后 dom 无法捕获的异常
            document.addEventListener("mouseup", function() {
                // 此时移除 鼠标移动监听,移除指定 事件函数
                flag = false;
                dom.removeEventListener("mousemove", fn);
            });

        }
    </script>
</body>

</html>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值