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:
import React from 'react';
import { Image, Group, Rect } from 'react-konva';
class CutoutImage extends React.Component {
state = {
image: null,
mask: null
}
componentDidMount() {
const image = new window.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>
<Image
image={this.state.image}
ref={node => { this.image = node; }}
/>
<Group
globalCompositeOperation={"destination-in"}
ref={node => {this.mask = node; }}
>
<Rect fill={"#555555"}
width={200} height={200}
x={100} y={100}
/>
<Rect fill={"#dddddd"}
width={200} height={200}
x={300} y={300}
/>
<Rect fill={"#dddddd"}
width={200} height={100}
x={150} y={350}
/>
</Group>
</Group>
)
}
}
export default CutoutImage;
And the result:
Post a Comment for "Using GlobalCompositeOperation To Mask Group Of Shapes, In React Konva"