JavaScript onmousedown и touchstart

Question:

Hello, I have a JavaScript code, but it is made only for the desktop version of browsers, I also need support for smartphones, here is the code:

window.onload = function() {

    canvas = document.getElementById("drawingCanvas");
    context = canvas.getContext("2d");


    // Подключаем требуемые для рисования события
    canvas.onmousedown = startDrawing;
    canvas.onmouseup = stopDrawing;
    canvas.onmouseout = stopDrawing;
    canvas.onmousemove = draw;

   //колір
   changeColor('rgb(0,86,166)', this);
}

The code of which does not need to be changed, this is in order to understand the essence of the presenter

function startDrawing(e) {
    // Начинаем рисовать
    isDrawing = true;

    // Создаем новый путь (с текущим цветом и толщиной линии)
    context.beginPath();

    // Нажатием левой кнопки мыши помещаем "кисть" на холст
    context.moveTo(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop);
}



/* рисование*/
function draw(e) {
    if (isDrawing == true)
    {
        // Определяем текущие координаты указателя мыши
        var x = e.pageX - canvas.offsetLeft;
        var y = e.pageY - canvas.offsetTop;

        // Рисуем линию до новой координаты
        context.lineTo(x, y);
        context.stroke();
    }
}


/* СТОП рисование*/
function stopDrawing() {
    isDrawing = false;
}

As I understand it, that piece needs to be changed:

canvas.onmousedown = startDrawing;
canvas.onmouseup = stopDrawing;
canvas.onmouseout = stopDrawing;
canvas.onmousemove = draw;

Answer:

The solution has been found!

Before this code:

canvas.onmousedown = startDrawing;
canvas.onmouseup  = stopDrawing;
canvas.onmouseout = stopDrawing;
canvas.onmousemove = draw;

You need to put (this is the connection of the reaction to the sensor):

canvas.addEventListener("touchstart", startDrawing, false);
canvas.addEventListener("touchend", stopDrawing, false);
canvas.addEventListener("touchcancel", stopDrawing, false);
canvas.addEventListener("touchmove", draw, false);
Scroll to Top
AllEscort