reactjskonvajskonvakonvajs-reactjs

How to apply transparency for several shapes at once on the React-konva?


https://konvajs.org/docs/sandbox/Transparent_Group.html

I saw the link above and tried to use group.cache() in react-konva, but I don't know how to apply it. Please tell me how.

import React from 'react';
import { Circle, Group, Layer, Rect, Stage } from 'react-konva';

const App = () => {
  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Group opacity={0.5} x={50} y={50}>
          <Rect width={100} height={100} fill="red" />
          <Circle width={100} height={100} radius={70} fill="greed" />
        </Group>
      </Layer>
    </Stage>
  );
};

export default App;


Solution

  • import React from 'react';
    import { Circle, Group, Layer, Rect, Stage } from 'react-konva';
    
    const App = () => {
      const groupRef = React.useRef();
    
      // this effect will run only once on mount
      // you may need to recache group on some internal updates
      React.useEffect(() => {
        groupRef.current.cache();
      }, []);
      return (
        <Stage width={window.innerWidth} height={window.innerHeight}>
          <Layer>
            <Group opacity={0.5} x={50} y={50} ref={groupRef}>
              <Rect width={100} height={100} fill="red" />
              <Circle width={100} height={100} radius={70} fill="greed" />
            </Group>
          </Layer>
        </Stage>
      );
    };
    
    export default App;