• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

107
Vistas
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

about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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 }}
/>
about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda