移动网页上Canvas如何获取触摸位置

8

我有一段代码,可以将一条线从(x,y)坐标拖到新的鼠标(x,y)坐标。在桌面浏览器中,这个代码可以正常工作,但是在移动端浏览器中却无法正常工作。我已经添加了触摸事件监听器,但是我猜测坐标可能出现了错误。以下是我的代码:

   function getMouse(e) {
     var element = canvas, offsetX = 0, offsetY = 0;
     if (element.offsetParent) {
       do {
         offsetX += element.offsetLeft;
         offsetY += element.offsetTop;
       } while ((element = element.offsetParent));
     }

     mx = (e.pageX - offsetX) - LINE_WIDTH;
     my =( e.pageY - offsetY )- LINE_WIDTH;
   }
   function mouseDown(e){
     getMouse(e);
     clear(fctx);
     var l = lines.length;
     for (var i = l-1; i >= 0; i--) {
       draw(fctx,lines[i]);
       var imageData = fctx.getImageData(mx, my, 1, 1);
       if (imageData.data[3] > 0) {
         selectedObject = lines[i];
         isDrag = true;
         canvas.onmousemove = drag;
         clear(fctx);
       }
     }
   }
   function mouseUp(){
     isDrag = false;
   }
   canvas.onmousedown = mouseDown;
   canvas.onmouseup = mouseUp;
   canvas.addEventListener('touchstart', mouseDown, false);
   canvas.addEventListener('touchend', mouseUp, false);

你可以在这里看到工作部分:http://codepen.io/nirajmchauhan/pen/yYdMJR
1个回答

11

从触摸事件生成鼠标事件

好的,我看到这个问题已经有一段时间了,没有人提供答案,我来提供一个。

与鼠标事件不同,触摸事件涉及许多与 UI 的接触点。为了适应这一点,触摸事件提供了一个触摸点的数组。由于鼠标不能同时处于两个位置,最好将这两种交互方法分别处理,以获得最佳的用户体验。由于您没有询问如何检测设备是触摸还是鼠标驱动的,我已经留给其他人来问。

处理两者

鼠标和触摸事件可以共存。在没有其中之一的设备上添加鼠标或触摸事件的侦听器不是问题。缺少的输入界面只是不会生成任何事件。这使得很容易为您的页面实现透明解决方案。

关键在于你喜欢哪个界面,并在该界面不可用时模拟该界面。在这种情况下,我将从创建的任何触摸事件中模拟鼠标。

通过编程创建事件。

代码使用 MouseEvent 对象创建和分派事件。它很容易使用,事件与真实的鼠标事件无法区分。有关 MouseEvent 的详细说明,请转到 MDN MouseEvent

最基本的操作。

创建一个鼠标单击事件并将其分派到文档中。

  var event = new MouseEvent( "click", {'view': window, 'bubbles': true,'cancelable': true});
  document.dispatchEvent(event);

您还可以将事件分派给单个元素。

  document.getElementById("someButton").dispatchEvent(event);

监听事件就像监听实际鼠标一样。

  document.getElementById("someButton").addEventListener(function(event){
        // your code
  ));
MouseEvent 函数的第二个参数是您可以添加有关事件的其他信息的位置。例如,clientXclientY 是鼠标的位置,或者 whichbuttons 表示按下的按钮。
如果您曾经查看过 mouseEvent,您将知道有很多属性。因此,发送到鼠标事件中的内容将取决于事件侦听器使用什么。 触摸事件。 触摸事件与鼠标类似。有 touchstarttouchmovetouchend。它们不同之处在于它们提供一个位置数组,每个接触点对应一个位置。不确定最大值是多少,但对于这个答案,我们只对一个感兴趣。有关完整详情,请参见 MDN touchEvent
我们需要做的是,对于仅涉及一个接触点的触摸事件,我们希望在相同位置生成相应的鼠标事件。如果触摸事件返回多个接触点,则我们无法知道它们的意图焦点在哪里,因此我们将简单地忽略它们。
function touchEventHandler(event){
    if (event.touches.length > 1){  // Ignor multi touch events
        return;
    }
}

现在我们知道,通过触摸单个联系人,我们可以根据触摸事件中的信息创建鼠标事件。

最基本的情况是这样的:

touch = event.changedTouches[0]; // get the position information
if(type === "touchmove"){        
    mouseEventType = "mousemove";   // get the name of the mouse event
                                    // this touch will emulate   
}else
if(type === "touchstart"){  
    mouseEventType = "mousedown";     // mouse event to create
}else
if(type === "touchend"){ 
    mouseEventType = "mouseup";     // ignore mouse up if click only
}

var mouseEvent = new MouseEvent( // create event
    mouseEventType,   // type of event
    {
        'view': event.target.ownerDocument.defaultView,
        'bubbles': true,
        'cancelable': true,
        'screenX':touch.screenX,  // get the touch coords 
        'screenY':touch.screenY,  // and add them to the 
        'clientX':touch.clientX,  // mouse event
        'clientY':touch.clientY,
});
// send it to the same target as the touch event contact point.
touch.target.dispatchEvent(mouseEvent);

现在您的鼠标监听器将接收 mousedown mousemove mouseup 事件,当用户在设备上仅在一个位置触摸时。 遗漏点击 到目前为止一切顺利,但有一个缺少的鼠标事件是必须的。 "onClick" 我不确定是否有等效的触摸事件,只是作为练习,我看到我们所拥有的足够信息来决定一组触摸事件是否可以视为单击。
这将取决于开始和结束触摸事件之间的距离有多远,超过几个像素就会成为拖动。它还会取决于持续时间。(虽然不同于鼠标)我发现人们倾向于轻击以进行单击操作,而鼠标可以保持按下,在释放时用于确认,或者拖动取消,这不是人们使用触摸界面的方式。
因此,我记录 touchStart 事件发生的时间。 event.timeStamp 和开始位置。然后在 touchEnd 事件中,我查找移动的距离和时间。如果它们都在我设置的限制范围内,我还会生成鼠标单击事件和鼠标释放事件。
这是将触摸事件转换为鼠标事件的基本方法。 一些代码 下面是一个名为mouseTouch的小型API,它执行我刚才解释的操作。它涵盖了简单绘图应用程序所需的最基本的鼠标交互。
//                                _______               _     
//                               |__   __|             | |    
//    _ __ ___   ___  _   _ ___  ___| | ___  _   _  ___| |__  
//   | '_ ` _ \ / _ \| | | / __|/ _ \ |/ _ \| | | |/ __| '_ \ 
//   | | | | | | (_) | |_| \__ \  __/ | (_) | |_| | (__| | | |
//   |_| |_| |_|\___/ \__,_|___/\___|_|\___/ \__,_|\___|_| |_|
//                                                            
//    
// Demonstration of a simple mouse emulation API using touch events.

// Using touch to simulate a mouse.
// Keeping it clean with touchMouse the only pubic reference.
// See Usage instructions at bottom.
var touchMouse = (function(){
    "use strict";
    var timeStart, touchStart, mouseTouch, listeningElement, hypot;


    mouseTouch = {};  // the public object 
    // public properties.
    mouseTouch.clickRadius = 3; // if touch start and end within 3 pixels then may be a click
    mouseTouch.clickTime = 200; // if touch start and end in under this time in ms then may be a click
    mouseTouch.generateClick = true; // if true simulates onClick event
                                     // if false only generate mousedown, mousemove, and mouseup
    mouseTouch.clickOnly = false; // if true on generate click events
    mouseTouch.status = "Started."; // just for debugging



    // ES6 new math function
    // not sure the extent of support for Math.hypot so hav simple poly fill
    if(typeof Math.hypot === 'function'){
        hypot = Math.hypot;
    }else{
        hypot = function(x,y){  // Untested 
            return Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
        };
    }
    // Use the new API and MouseEvent object
    function triggerMouseEvemt(type,fromTouch,fromEvent){
      var mouseEvent = new MouseEvent(
          type, 
          {
              'view': fromEvent.target.ownerDocument.defaultView,
              'bubbles': true,
              'cancelable': true,
                'screenX':fromTouch.screenX,
                'screenY':fromTouch.screenY,
                'clientX':fromTouch.clientX,
                'clientY':fromTouch.clientY,
                'offsetX':fromTouch.clientX, // this is for old Chrome 
                'offsetY':fromTouch.clientY,
                'ctrlKey':fromEvent.ctrlKey,
                'altKey':fromEvent.altKey,
                'shiftKey':fromEvent.shiftKey,
                'metaKey':fromEvent.metaKey,
                'button':0,
                'buttons':1,
          });
        // to do.
        // dispatch returns cancelled you will have to 
        // add code here if needed
        fromTouch.target.dispatchEvent(mouseEvent);
    }

    // touch listener. Listens to Touch start, move and end.
    // dispatches mouse events as needed. Also sends a click event
    // if click falls within supplied thresholds and conditions
    function emulateMouse(event) {

        var type, time, touch, isClick, mouseEventType, x, y, dx, dy, dist;
        event.preventDefault();  // stop any default happenings interfering
        type = event.type ;  // the type.

        // ignore multi touch input
        if (event.touches.length > 1){
            if(touchStart !== undefined){ // don't leave the mouse down
                triggerMouseEvent("mouseup",event.changedTouches[0],event);
            }
            touchStart = undefined;
            return;
        }
        mouseEventType = "";
        isClick = false;  // default no click
        // check for each event type I have the most numorus move event first, Good practice to always think about the efficancy for conditional coding.
        if(type === "touchmove" && !mouseTouch.clickOnly){        // touchMove
            touch = event.changedTouches[0];
            mouseEventType = "mousemove";      // not much to do just move the mouse
        }else
        if(type === "touchstart"){  
            touch = touchStart = event.changedTouches[0]; // save the touch start for dist check
            timeStart = event.timeStamp; // save the start time
            mouseEventType = !mouseTouch.clickOnly?"mousedown":"";     // mouse event to create
        }else
        if(type === "touchend"){  // end check time and distance
            touch =  event.changedTouches[0];
            mouseEventType = !mouseTouch.clickOnly?"mouseup":"";     // ignore mouse up if click only
            // if click generator active
            if(touchStart !== undefined && mouseTouch.generateClick){
                time = event.timeStamp - timeStart;  // how long since touch start
                // if time is right
                if(time < mouseTouch.clickTime){
                    // get the distance from the start touch
                    dx = touchStart.clientX-touch.clientX;
                    dy = touchStart.clientY-touch.clientY;
                    dist = hypot(dx,dy);
                    if(dist < mouseTouch.clickRadius){
                        isClick = true;
                    }
                }
            }
        }
        // send mouse basic events if any
        if(mouseEventType !== ""){
            // send the event
            triggerMouseEvent(mouseEventType,touch,event);
        }
        // if a click also generates a mouse click event
        if(isClick){
            // generate mouse click
            triggerMouseEvent("click",touch,event);
        }
    }

    // remove events
    function removeTouchEvents(){
        listeningElement.removeEventListener("touchstart", emulateMouse);
        listeningElement.removeEventListener("touchend", emulateMouse);
        listeningElement.removeEventListener("touchmove", emulateMouse);
        listeningElement = undefined;  

    }

    // start  adds listeners and makes it all happen.
    // element is optional and will default to document.
    // or will Listen to element.
    function startTouchEvents(element){
        if(listeningElement !== undefined){ // untested
            // throws to stop cut and past useage of this example code.
            // Overwriting the listeningElement can result in a memory leak.
            // You can remove this condition block and it will work
            // BUT IT IS NOT RECOGMENDED

            throw new ReferanceError("touchMouse says!!!! API limits functionality to one element.");
        }
        if(element === undefined){
            element = document;
        }
        listeningElement = element;
        listeningElement.addEventListener("touchstart", emulateMouse);
        listeningElement.addEventListener("touchend", emulateMouse);
        listeningElement.addEventListener("touchmove", emulateMouse);
    }

    // add the start event to public object.
    mouseTouch.start = startTouchEvents;
    // stops event listeners and remove them from the DOM 
    mouseTouch.stop = removeTouchEvents;

    return mouseTouch;

})(); 











// How to use

touchMouse.start(); // done using defaults will emulate mouse on the entier page 

// For one element and only clicks
// HTML
<input value="touch click me" id="touchButton" type="button"></input>
// Script
var el = document.getElementById("touchButton");
if(el !== null){
    touchMouse.clickOnly = true;
    touchMouse.start(el);
}

// For drawing on a canvas
<canvas id="touchCanvas"></canvas> 
// script
var el = document.getElementById("touchButton");
if(el !== null){
    touchMouse.generateClick = false; // no mouse clicks please
    touchMouse.start(el);
}

// For switching elements call stop then call start on the new element
// warning touchMouse retained a reference to the element you
// pass it with start. Dereferencing touchMouse will not delete it.
// Once you have called start you must call stop in order to delete it.

// API
//---------------------------------------------------------------
// To dereference call the stop method if you have called start . Then dereference touchMouse
// Example
touchMouse.stop();
touchMouse = undefined;


// Methods.
//---------------------------------------------------------------
// touchMouse.start(element); // element optional. Element is the element to attach listeners to.
                              // Calling start a second time without calling stop will
                              // throw a reference error. This is to stop memory leaks.
                              // YOU Have been warned...

// touchMouse.stop();          // removes listeners and dereferences any DOM objects held
//---------------------------------------------------------------
// Properties
// mouseTouch.clickRadius = 3; // Number. Default 3. If touch start and end within 3 pixels then may be a click
// mouseTouch.clickTime = 200; // Number. Default 200. If touch start and end in under this time in ms then may be a click
// mouseTouch.generateClick;   // Boolean. Default true. If true simulates onClick event
//                                    // if false only generate mousedown, mousemove, and mouseup
// mouseTouch.clickOnly;      // Boolean.  Default false. If true only generate click events Default false
// mouseTouch.status;         // String. Just for debugging kinda pointless really. 

希望这能对你的代码有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接