在手机上与画布互动时避免滚动
我正在尝试使用触摸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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试不
touch
操作,以下是Canvas
使用Pointer
事件的代码的重构,以及用于禁用touch> touch 操作:
You may try without
touch
actions, here is a refactor ofcanvas
code usingpointer
events and a style rule for disablingtouch
actions: