Javascript 在React Konva中使用globalCompositeOperation遮罩一组形状
我的项目使用React Konva() 我正在尝试将多个形状绘制到一个Javascript 在React Konva中使用globalCompositeOperation遮罩一组形状,javascript,reactjs,html5-canvas,konvajs,Javascript,Reactjs,Html5 Canvas,Konvajs,我的项目使用React Konva() 我正在尝试将多个形状绘制到一个组中,并使用它来遮罩“下面”的图像 当我的组件在应用了globalCompositeOperation的情况下绘制单个形状时,它会生成预期的结果。代码如下: render() { return ( <Group > <Group> <Image
组中
,并使用它来遮罩“下面”的图像
当我的组件在应用了globalCompositeOperation
的情况下绘制单个形状时,它会生成预期的结果。代码如下:
render() {
return (
<Group >
<Group>
<Image
image={this.state.image}
ref={node => { this.image = node; }}
/>
<Group>
<Rect fill={"#555555"}
width={200} height={200}
x={100} y={100}
globalCompositeOperation={"destination-in"}
/>
</Group>
</Group>
</Group>
)
}
<Group>
<Image
image={this.state.image}
ref={node => { this.image = node; }}
/>
<Group globalCompositeOperation={"destination-in"}>
<Rect fill={"#555555"}
width={200} height={200}
x={100} y={100}
/>
</Group>
</Group>
结果是:
这很奇怪,因为Konva文档表明Group
实际上有一个属性globalCompositeOperation
(请参阅)
你知道如何让Konva在
组
级别而不仅仅是形状
级别应用全局复合操作
吗?啊,刚刚找到了解决方案
在应用globalCompositeOperation
之前,似乎需要缓存整个组。我假设这意味着组首先被展平/光栅化
在我的React组件中,我实现了如下解决方案:
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;
从“React”导入React;
从“react konva”导入{Image,Group,Rect};
类CutoutImage扩展了React.Component{
状态={
图像:空,
掩码:空
}
componentDidMount(){
const image=new window.image();
image.src=“/images/frisbee.jpg”;
image.onload=()=>{
this.setState({image});
}
}
componentDidUpdate(){
如果(此图像){
this.image.cache();
}
如果(此.mask){
this.mask.cache();
}
}
render(){
返回(
{this.image=node;}}
/>
{this.mask=node;}}
>
)
}
}
导出默认剪切图像;
结果是: