簡體   English   中英

用於觸摸設備的畫布繪圖應用

[英]Canvas drawing app for touch devices

哈羅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);

`

觸摸事件行為異常的問題通常來自觸摸事件和鼠標事件的工作方式之間的差異。 一次只能發生一個鼠標事件,因為只有一個鼠標指針。 另一方面,觸摸事件需要處理多點觸摸事件。 例如,一根手指下降,它移動,然后另一根下降。 現在,我們有2個touchstart事件和1個touch move事件。 它很快變得非常復雜。

我忘了從現在開始得到的信息(抱歉,原始作者),但這是我在一個應用程序中使用的代碼。 該功能附加到所有三種類型的觸摸事件-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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM