'How to draw with touchscreen via js events?

I`m trying to create drawing canvas that can be used on mobile phones

window.onload = function () {
    canvas = document.getElementById("drawingCanvas");
    context = canvas.getContext("2d");

    canvas.ontouchstart = touch;
    canvas.ontouchcancel = untouch;
    canvas.ontouchend = untouch;
    canvas.ontouchmove = touchdraw;
}

I have this code to setup touch events

function touch(e) {
    isTouch = true;

    context.beginPath();

    context.moveTo(e.originalEvent.touches[0].pageX - canvas.offsetLeft, e.originalEvent.touches[0].pageY - canvas.offsetTop);
}

function untouch(e) {
   
    isTouch = false;
}

function touchdraw(e) {

    if (isTouch == true) {

        var x = e.originalEvent.touches[0].pageY - canvas.offsetTop;
        var y = e.originalEvent.touches[0].pageX - canvas.offsetLeft;

        context.lineTo(x, y);
        context.stroke();
    }
}

and this is my event functions

I try to make this like mouse events But it doesn`t work



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source