So I am currently trying to create a notebook styled module for a web application. Currently it is working perfectly fine with its mouse event but not when using touch events.

//TOUCH LISTENER
theCanvas.addEventListener("touchstart", startT, false);
theCanvas.addEventListener("touchend", endT, false);
theCanvas.addEventListener("touchmove", moveT, false);

//MOUSE LISTENER
theCanvas.addEventListener("mousedown", start);
theCanvas.addEventListener("mouseup", end);
theCanvas.addEventListener("mousemove", move, false);

//MOUSE EVENTS
function start(event) {
  if (event.button === MAIN_MOUSE_BUTTON) {
    shouldDraw = true;

        setLineProperties(theContext);

        theContext.beginPath();

    let elementRect = event.target.getBoundingClientRect();
        theContext.moveTo(event.clientX - elementRect.left, event.clientY - elementRect.top);

        console.log(PenType(mode));
  }
}

function end(event) {
  if (event.button === MAIN_MOUSE_BUTTON) {
    shouldDraw = false;
  }
}

function move(event) {
  if (shouldDraw) {
    let elementRect = event.target.getBoundingClientRect();
    theContext.lineTo(event.clientX - elementRect.left, event.clientY - elementRect.top);
        theContext.stroke()

  }
}

//TOUCH EVENTS
function startT(event) {
    event.preventDefault();
    shouldDraw = true;

    setLineProperties(theContext);

    theContext.beginPath();

    let elementRect = event.target.getBoundingClientRect();
    theContext.moveTo(event.clientX - elementRect.left, event.clientY - elementRect.top);

    console.log(PenType(mode));
}

function endT(event) {
  if (event.touches.length == 1) {
        event.preventDefault();
    shouldDraw = false;
  }
}

function moveT(event) {
  if (shouldDraw) {
        event.preventDefault();
    let elementRect = event.target.getBoundingClientRect();
    theContext.lineTo(event.clientX - elementRect.left, event.clientY - elementRect.top);
        theContext.stroke()
  }
}

While the mouse event is fully functional and allow drawing on the canvas. The touch events has only the a small space near the left and top border of the canvas that can be drawn on, and it is only when u tap on the border, just a dot. It should have worked like the mouse event

1 Answers

0
PopHip On Best Solutions

Since touch event can handle multiple touch points, the x and y of the fingers are not described by event.clientX and event.clientY like for mouse. Instead you got event.touches which is an array of coordinates. So in your code, everytime you want to handle touch event, just replace event.clientX by event.touches[0].clientX and event.clientY by event.touches[0].clientY (considering you only want to handle one finger of course)