react-konvakonva

How to fire onmouseup event outside stage when doing free draw in react-konva


I am implementing free draw function through react-konva. It starts drawing with the mousedown event and continues drawing with the mousemove event. The mouseup event terminates the drawing operation. However, the mouseup event works normally within the stage area, but does not work outside the canvas area. How can I make the mouseup event work even outside the stage area?

    <Stage
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
    >

Solution

  • Instead of listening mouseup/mousemove on stage, you can listen on global window object. In react you can do something like this:

    const App = () => {
      const handleMouseUp = React.useCallback(() => {
        // your code here
      }, []);
      React.useEffect(() => {
        window.addEventListener('mouseup', handleMouseUp);
        return () => {
          window.removeEventListener('mouseup', handleMouseUp);
        }
      }, [handleMouseUp]);
      return (
        <Stage
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
        >
      );
    }