基于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;