如何从javascript触摸事件获取滑动角度

时间:2017-06-30 20:26:42

标签: javascript touch

我有以下代码:

swipeDetect = function(el, callback){

    var touchsurface = el,
    swipedir,
    startX,
    startY,
    distX,
    distY,
    threshold = 7, //required min distance traveled to be considered swipe
    restraint = 100, // maximum distance allowed at the same time in perpendicular direction
    allowedTime = 500, // maximum time allowed to travel that distance
    maxangle=40,
    elapsedTime,
    startTime,
    touchinprocess=false,
    handleswipe = callback || function(swipedir){};

    touchsurface.addEventListener('touchstart', function(e){

        touchinprogress = true;
        var touchobj = e.changedTouches[0];
        swipedir = 'none';
        dist = 0;
        startX = touchobj.pageX;
        startY = touchobj.pageY;
        startTime = new Date().getTime();
    }, false);

    touchsurface.addEventListener('touchmove', function(e){


        var touchobj = e.changedTouches[0];
        distX = startX - touchobj.pageX;
        distY = startY - touchobj.pageY;
        rads = Math.atan(distY,distX);
        var deg = rads * (180 / 3.14);
        console.log(deg);
        if (Math.abs(distY) > restraint && Math.abs(deg) > maxangle) e.preventDefault();

    }, false);

    touchsurface.addEventListener('touchend', function(e){

        var touchobj = e.changedTouches[0];
        distX = touchobj.pageX - startX;
        distY = touchobj.pageY - startY;
        elapsedTime = new Date().getTime() - startTime;

        if (elapsedTime <= allowedTime){ // first condition for awipe met
            if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){ // 2nd condition for horizontal swipe met
                swipedir = (distX < 0)? 'left' : 'right'; // if dist traveled is negative, it indicates left swipe
            }
            else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ // 2nd condition for vertical swipe met
                swipedir = (distY < 0)? 'up' : 'down'; // if dist traveled is negative, it indicates up swipe
            };
        };
        handleswipe(e,swipedir);
        return true;
    }, false);
},

我试图在触摸移动功能中获得触摸滑动的角度(如果滑动超过一定度数,则终止默认滚动)。但它不断输出80左右的数字。无论我如何刷卡。这有什么不对?

我正在使用它进行图像扫描,我想让用户滑动,而不是让它同时滚动和滑动。

也许我说这一切都错了。

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

Math.atan(x) [1]函数只接受一个参数,在你的情况下应该是y与x之比:

rads = Math.atan(distY/distX);

可能很难看出差异,但在初始代码中,您有,而不是/。我用这个改变运行你的代码,它工作。请记住,Math.atan2(y,x)确实有两个参数。

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan

答案 1 :(得分:0)

我做了一些测试,我认为问题可能出在你的atan功能上。试试atan2?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2

这似乎对我有用。