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
onm ouseDown={drawStart}
onTouchStart={drawStart}
onm ouseUp={drawEnd}
onTouchEnd={drawEnd}
onm ouseMove={draw}
onTouchMove={draw}
ref={canvasRef}
/>
)
This component works perfectly when using mouse functionality on non-mobile
CodePudding user response:
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 }}
/>