Search code examples
javascriptcanvastouch

How to change mouse functions to touch in JS canvas


Made a simple paint in Javascript. However it is not working in mobile.

Is there an easy "transformation" from desktop to touchscreens?

I tried to change mouse actions like mousemove to touchmove without progress.

$('#canvas').mousedown(function(e)  {
    var mouseX = e.pageX - this.offsetLeft;
    var mouseY = e.pageY - this.offsetTop;

    paint = true;
    addClick(mouseX, mouseY, false);
    redraw();
});

$('#canvas').mousemove(function(e){
    if(paint==true){
        addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
        redraw();
    }
});

$('#canvas').mouseup(function(e){
    paint = false;
    redraw();
});

$('#canvas').mouseleave(function(e){
    paint = false;
});

Solution

  • There is no easy "transformation" unfortunately. For the most part you would have to change the structure.

    This article is great and elaborates more on what sort of structure you should have when implementing touch functionality in Canvas.

    http://bencentra.com/code/2014/12/05/html5-canvas-touch-events.html