如何用 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)