'avoid scrolling when interacting with canvas on mobile

I'm trying to allow drawing using touch on the HTML canvas, but it scrolls the window when I try to draw. I've tried using preventDefault() on the event functions, but I get the error: Unable to preventDefault inside passive event listener invocation.

My canvas component looks like:

  const drawStart = (e) => {
    const { offsetX, offsetY } = e.nativeEvent
    contextRef.current.beginPath()
    contextRef.current.moveTo(offsetX, offsetY)
    contextRef.current.lineTo(offsetX, offsetY)
    contextRef.current.stroke()
    setDrawing(true)
  }

  const drawEnd = () => {
    contextRef.current.closePath()
    setDrawing(false)
  }

  const draw = (e) => {
    e.preventDefault()
    if (!drawing) {
      return
    }
    const { offsetX, offsetY } = e.nativeEvent
    contextRef.current.lineTo(offsetX, offsetY)
    contextRef.current.stroke()
  }

  return (
    <canvas
      onMouseDown={drawStart}
      onTouchStart={drawStart}
      onMouseUp={drawEnd}
      onTouchEnd={drawEnd}
      onMouseMove={draw}
      onTouchMove={draw}
      ref={canvasRef}
    />
  )

This component works perfectly when using mouse functionality on non-mobile



Solution 1:[1]

You may try without touch actions, here is a refactor of canvas code using pointer events and a style rule for disabling touch actions:

<canvas
  onPointerDown={drawStart}
  onPointerUp={drawEnd}
  onPointerMove={draw}
  ref={canvasRef}
  style={{ touchAction: none }}
/>

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 syduki