跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • 如何用 react hooks 封装一个鼠标绘图组件?
未分類
28 11 月 2020

如何用 react hooks 封装一个鼠标绘图组件?

如何用 react hooks 封装一个鼠标绘图组件?

資深大佬 : weimo383 3

这是我想要封装的一个鼠标画图组件,不停的触发 mouseMove 获取当前的位置,同时又缓存了上一次的位置,连接两个点即可,但是我想要用 hooks 封装,感觉很难,没有头绪。

// When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0;  const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d');  // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas.  // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => {   x = e.offsetX;   y = e.offsetY;   isDrawing = true; });  myPics.addEventListener('mousemove', e => {   if (isDrawing === true) {     drawLine(context, x, y, e.offsetX, e.offsetY);     x = e.offsetX;     y = e.offsetY;   } });  window.addEventListener('mouseup', e => {   if (isDrawing === true) {     drawLine(context, x, y, e.offsetX, e.offsetY);     x = 0;     y = 0;     isDrawing = false;   } });  function drawLine(context, x1, y1, x2, y2) {   context.beginPath();   context.strokeStyle = 'black';   context.lineWidth = 1;   context.moveTo(x1, y1);   context.lineTo(x2, y2);   context.stroke();   context.closePath(); } 

这是我写出来的完全不能画图的 hook (我估计是因为没有像上面那样获取上次位置和当前位置的原因

const Canvas = () => {     const canvasRef = React.useRef(null);     //const [paths, setPaths] = useState([]);     const [isDrawing, setIsDrawing] = useState(false);     const [pos, setPos] = useState({         x: 0,         y: 0,     });     const [isMouseDown, setIsMouseDown] = useState(false);     const [isMouseMove, setIsMouseMove] = useState(false);     const [isMouseUp, setIsMouseUp] = useState(false);     useEffect(() => {         const ctx = canvasRef.current.getContext("2d");         if (isDrawing) {             console.log("isDrawing");             ctx.beginPath();             ctx.strokeStyle = 'black';             ctx.lineWidth = 1;             ctx.lineTo(pos.x, pos.y);             ctx.stroke();             ctx.closePath();         }     }, [isMouseDown, isDrawing, pos]);     const handleMouseDown = (e) => {         setPos({             x: e.clientX,             y: e.clientY,         });         setIsDrawing(true);         setIsMouseDown(true);     }      const handleMouseUp = () => {         setIsDrawing(false);         setIsMouseUp(false);     }     const handleMouseMove = (e) => {         // console.log(e);         setIsMouseMove(true);         setPos({             x: e.clientX,             y: e.clientY,         });         //console.log(state.ctx);     }     return (         <div className="back-div" >             <canvas ref={canvasRef} id="canvas1" className="paint-canvas" onMouseDown={handleMouseDown} onMouseMove={handleMouseMove} onMouseUp={handleMouseUp}>             </canvas>         </div>     ) } 

大佬有話說 (17)

  • 主 資深大佬 : weimo383

    顺带一提,我的 e.offsetX 为什么读出来是 undefined

  • 主 資深大佬 : weimo383

    啊,别沉啊

  • 資深大佬 : frankwei777

    react 的 offsetX 在 event.nativeEvent 中

  • 資深大佬 : shenyu1996

    https://codesandbox.io/s/busy-saha-rs7f9
    稍稍改了一下 可以了

  • 主 資深大佬 : weimo383

    @frankwei777 谢谢

  • 主 資深大佬 : weimo383

    @shenyu1996 谢谢!

  • 資深大佬 : v135ex

    有啥难的,自己多想想就写出来了

  • 主 資深大佬 : weimo383

    @v135ex
    还是有点难的,你可以试试,css 改动 canvas 大小的话鼠标位置和 canvas 上绘图坐标是不一致的

  • 資深大佬 : IamJ

    @weimo383 用标签属性设置大小而不是样式

  • 資深大佬 : v135ex

    @weimo383 好的 没有尝试过妄下定论了,我也尝试下学习一下

  • 資深大佬 : xrr2016

    我的建议是用成熟的绘图库,例如 p5.js 这种,然后在用 hooks 做你需要的功能

  • 主 資深大佬 : weimo383

    @xrr2016 主要是还是不想依赖外部库(增加负担)

  • 資深大佬 : funnyecho

    个人看法,这里用 react hook ( useState )其实没有什么意义,你第一段代码都自成一体了,直接使用事件驱动来的更快,不需要额外等待 react setState 的调度。

    与其说使用 hook,不如把第一段代码封装成一个纯函数,接受一个 ref 来处理绘图,在外部 FC 中调用这个函数来的更好。

  • 主 資深大佬 : weimo383

    @funnyecho ref 可以在组件中传递吗?
    大佬能不能再具体一些哈

  • 資深大佬 : funnyecho

    @weimo383

    把第一段代码封装成函数:
    “`
    // 函数接受一个 canvas element,并返回 destructor 函数用来 removeListener
    type draw = ($canvas) => (() => void)
    “`

    然后,React.FC 中调用 draw 方法,举个例子:
    “`
    useEffect(() => {

    return draw(canvasRef.current)
    }, [canvasRef.current])
    “`

  • 主 資深大佬 : weimo383

    @funnyecho 我的组件得要能够保存绘制历史记录,所以副作用和状态是相关的

  • 資深大佬 : funnyecho

    @weimo383 看代码就几个状态,每次 mousedown 都会重置,保存在 draw 函数内部的作用域就好了呀。

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具