知识学堂 > 课程 > JS长按事件

JS长按事件

发布日期:2022/3/8 来源:聚恒【返回】

  <script>
        var touchY = 0;
        var longClick = 0;
        $(".xianshi").on({
            touchstart: function (e) {
                longClick = 0;
                timeOutEvent = setTimeout(function () {
                                    //此处为长按事件-----在此显示遮罩层及删除按钮----生成图片开始
                                   var canvas2 = document.createElement("canvas");
                    var _canvas = document.querySelector('.Share'); //需要替换成图片的html区域
                    //获取宽高
                    var w = parseInt(window.getComputedStyle(_canvas).width);
                    var h = parseInt(window.getComputedStyle(_canvas).height);
                    
                    //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
                    canvas2.width = w * window.devicePixelRatio;
                    canvas2.height = h * window.devicePixelRatio;
                    canvas2.style.width = w + "px";
                    canvas2.style.height = h + "px";




                    //可以按照自己的需求,对context的参数修改,translate指的是偏移量
                    //  var context = canvas.getContext("2d");
                    //  context.translate(0,0);
                    var context = canvas2.getContext("2d");
                    // context.translate(1,1);
                    context.scale(window.devicePixelRatio, window.devicePixelRatio);
                    context.translate(-window.screen.width * 0.1, -window.screen.height * 0.02);//用于需要截图的不是全屏的情况
            
                  


                    html2canvas(_canvas, { canvas: canvas2 }).then(function (canvas) {
                        var imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url
                        $(".Share").html('<img class="down" src="' + imgUri + '" style="width:' + w + 'px;">');
                    })
                });




                console.log(window.devicePixelRatio)

                    //生成图片结束
                    longClick = 1;//假如长按,则设置为1
                }, 500);
                var touch = e.touches[0];
                touchY = touch.clientY;
            },
            touchmove: function () {
                clearTimeout(timeOutEvent);
                timeOutEvent = 0;
                var touch = e.touches[0]
                if (Math.abs(touch.clientY - touchY) < 10) {
                    e.preventDefault();
                }
            },
            touchend: function (e) {
                clearTimeout(timeOutEvent);
                if (timeOutEvent != 0 && self.longClick == 0) {//点击
                    //此处为点击事件----在此处添加跳转详情页


                }
                return false;
            }
        });
    </script>