Skip to content Skip to sidebar Skip to footer

Using Globalcompositeoperation To Mask Group Of Shapes, In React Konva

My project uses React Konva (https://github.com/konvajs/react-konva) I am trying to draw multiple shapes into a Group and use this to mask the image 'below'. When my component draw

Solution 1:

Ah, just found the solution.

It seems that the entire Group needs to be cached before the globalCompositeOperation is applied. I am assuming this means that the Group gets flattened/rasterised first.

In my React component, I achieved the solution as follows:

importReactfrom'react';
import { Image, Group, Rect } from'react-konva';

classCutoutImageextendsReact.Component {
    state = {
        image: null,
        mask: null
    }

    componentDidMount() {
        const image = newwindow.Image();
        image.src = "/images/frisbee.jpg";
        image.onload = () => {
            this.setState({ image });
        }
    }

    componentDidUpdate() {
        if (this.image) {
            this.image.cache();
        }
        if (this.mask) {
            this.mask.cache();
        }
    }

    render() {
        return (

            <Group><Imageimage={this.state.image}ref={node => { this.image = node; }} 
                />
                <GroupglobalCompositeOperation={"destination-in"} 
                    ref={node => {this.mask = node; }}
                    >
                    <Rectfill={"#555555"} 
                        width={200}height={200}x={100}y={100} 
                    /><Rectfill={"#dddddd"} 
                        width={200}height={200}x={300}y={300} 
                    /><Rectfill={"#dddddd"} 
                        width={200}height={100}x={150}y={350} 
                    /></Group></Group>
        )

    }

}
exportdefaultCutoutImage;

And the result:

enter image description here

Post a Comment for "Using Globalcompositeoperation To Mask Group Of Shapes, In React Konva"