我的项目使用React Konva (https://github.com/konvajs/react-konva)
我正在尝试绘制多个形状到一个Group,并使用它来遮罩图像“下面”。
当我的组件绘制一个应用了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>
)
}结果是:

请注意图像是如何裁剪到矩形的,从而显示出下面的文本层。
但是,一旦形状在组中移动,并且我在那里应用了globalCompositeOperation,就不会发生掩码。代码的相关部分:
<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 (请参阅https://konvajs.github.io/api/Konva.Group.html#globalCompositeOperation__anchor)。
你知道如何让(React) Konva在Group级别而不仅仅是Shape级别应用globalCompositeOperation吗?
发布于 2018-09-04 23:51:50
啊,刚刚找到解决方案了。
在应用globalCompositeOperation之前,似乎需要缓存整个Group。我假设这意味着组首先被扁平化/栅格化。
在我的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;结果是:

https://stackoverflow.com/questions/52169662
复制相似问题