在手机上与画布互动时避免滚动

发布于 2025-01-28 16:40:13 字数 976 浏览 2 评论 0原文

我正在尝试使用触摸html画布上的绘画,但是当我尝试绘制时,它会滚动窗口。我已经尝试在事件函数上使用dextDefault(),但是我会发现错误:无法在被动事件侦听器调用中预防默认面。

我的帆布组件看起来像:

  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}
    />
  )

在非移动机上使用鼠标功能时,此组件在

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三生殊途 2025-02-04 16:40:13

您可以尝试不touch操作,以下是Canvas使用Pointer事件的代码的重构,以及用于禁用touch> touch 操作:

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

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 }}
/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文