[英]How can I tint an image with react-konva?
根据 Konva 网站上的URLImage 示例,我创建了一个使用事件侦听器将图像加载到画布中的类。
我有一个完全由透明背景上的白色像素组成的 PNG。 我想将白色像素着色为纯色(例如,红色、紫色或青色)。 我看过过滤器示例,但我无法理解这些特定部分如何组合在一起。
我如何使用 react-konva.Image (使用,例如, <Image filters={[...]} image={...} ref={node => {this.imageNode = node;} />
)?
这是我上面提到的 TypeScript 类:
// import Konva from 'konva';
import React from 'react';
import {Image} from 'react-konva';
type ImgProps = {
color?: string,
src: string,
x?: number,
y?: number,
};
type ImgState = {
image: any,
};
class Img extends React.Component<ImgProps, ImgState> {
private image: HTMLImageElement | undefined;
// private imageNode: Konva.Image | null = null;
constructor(props: any) {
super(props);
this.state = {
image: undefined,
};
}
public componentDidMount = () => {
this.loadImage();
}
public componentDidUpdate = (oldProps: ImgProps) => {
if (oldProps.src !== this.props.src) {
this.loadImage();
}
}
public componentWillUnmount = () => {
if (this.image) {
this.image.removeEventListener('load', this.handleLoad);
}
}
public render = (): React.ReactNode => {
return (
<Image
image={this.state.image}
// ref={node => {this.imageNode = node;}}
x={this.props.x}
y={this.props.y}
/>
);
}
private loadImage = () => {
// Save to `this` to remove `load` handler on unmount.
this.image = new window.Image();
this.image.src = this.props.src;
this.image.addEventListener('load', this.handleLoad);
}
private handleLoad = () => {
// After setState react-konva will update canvas and redraw the layer
// because the `image` property has changed.
this.setState({
image: this.image,
});
// if (this.imageNode) {
// ...
// }
};
}
export default Img;
我想到了。 使用可以通过 ref 设置的Konva.Image
对象,如问题所示,您必须执行以下操作:
this.imageNode.cache();
this.imageNode.red(255);
this.imageNode.green(0);
this.imageNode.blue(0);
在上面的类示例中,这可以在handleLoad
函数中,或者可以访问此对象的任何地方。
然后使用filters
属性进行渲染,如下例所示,其中Image
是一个Konva.Image
对象:
<Image
image={this.state.image}
filters={[Konva.Filters.RGB]}
ref={node => {this.imageNode = node;}}
/>
Konva.Image.cache()
的文档说明(重点是我的):
缓存节点以提高绘图性能、应用过滤器或创建更准确的命中区域。 对于所有基本形状,将自动检测缓存画布的大小。
要将过滤器应用于
Konva.Image
,我们必须先使用cache()
函数对其进行cache()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.