用于触摸设备的画布绘图应用程序

时间:2015-08-24 14:16:46

标签: javascript html5 canvas

Hallo stackoverflooow社区,我的小绘图应用程序有点问题。它在桌面上工作得很好,但在触控设备上却不行。该应用程序只是在我触摸显示屏时提出一个观点。我希望有人可以帮助我。

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var radius = 5;
context.lineWidth = radius*2;
var press = false;

var putPoint = function(e){
    if(press){
    context.beginPath();
    context.arc(e.offsetX, e.offsetY, radius, 0, 2*Math.PI);
    context.fill();
    }
}

var start = function(e){
    press = true;
    putPoint(e);
    context.beginPath();
    context.moveTo(e.offsetX, e.offsetY);
}

var move = function(e){
    context.lineTo(e.offsetX, e.offsetY);
    context.stroke();
    putPoint(e);
    context.beginPath();
    context.moveTo(e.offsetX, e.offsetY);
}

var stop = function(){
press = false;
context.beginPath();
}

//mouse
canvas.addEventListener('mousedown', start);
canvas.addEventListener('mousemove', move);
canvas.addEventListener('mouseup', stop);

//touch
canvas.addEventListener('touchstart', start);
canvas.addEventListener('touchmove', move);
canvas.addEventListener('touchend', stop);

`

1 个答案:

答案 0 :(得分:0)

行为不当的触摸事件的问题通常来自触摸事件和鼠标事件的工作方式之间的差异。鼠标事件一次只发生一次,因为只有一个鼠标指针。另一方面,触摸事件需要处理多点触控事件。例如,一根手指下降,它移动,然后另一根手指下降。我们现在有2个touchstart事件和1个触摸移动事件。它变得相当复杂很快。

我忘了从现在开始的地方,(对不起原作者),但这是我在我的一个应用程序中使用的代码。该功能附加到所有三种类型的触摸事件 - touchstart,touchmove和touchend。它不涉及多点触摸,只是忽略当多个手指触摸输入设备时发生的任何事件。然后它创建一个合成鼠标事件,然后将其传递给普通的鼠标事件处理程序。

function onCanvasTouch(evt)
{
    if (evt.touches.length > 1 )
        return;

    if ((evt.type == "touchend" && evt.touches.length > 0))
    {
        evt.preventDefault();
        return;
    }

    evt.preventDefault();

    var newEvt = document.createEvent("MouseEvents");
    var type = null;
    var touch = null;
    switch (evt.type)
    {
        case "touchstart":
            type = "mousedown";
            touch = evt.changedTouches[0];
            break;
        case "touchmove":
            type = "mousemove";
            touch = evt.changedTouches[0];
            break;
        case "touchend":
            type = "mouseup";
            touch = evt.changedTouches[0];
            break;
    }

    newEvt.initMouseEvent(
                            type, true, true, evt.target, 0,
                            touch.screenX, touch.screenY, touch.clientX, touch.clientY,
                            evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null
                        );

    evt.target.dispatchEvent(newEvt);
}
相关问题