我正在尝试创建一个用户可以在图像或背景颜色上添加文本的应用程序。一切正常,但是当图像在画布中并且我想将图像更改为背景颜色时,我无法清除背景图像,以便我可以在其上显示背景颜色和文本。
这就是我所期待的,http://jsbin.com/sukuvoqahi/edit?js,output,我可以使用vanilla javascript但不能使用reactjs
这是我的reactjs代码
class ImageBoard extends React.PureComponent {
constructor() {
super();
this.state = {
canvas: undefined,
selected: undefined,
textVisible: false
};
}
componentDidMount() {
const canvas = new fabric.Canvas(this.canvasEl);
canvas.on("object:selected", e => this.setState({ selected: e.target }));
canvas.on("selection:cleared", e => this.setState({ selected: undefined }));
this.setState({ canvas: canvas });
this.setCanvasBackground(this.props.getSelectedImage.selectedImage, canvas);
}
componentWillReceiveProps(nextProps, nextState) {
if (nextProps.getSelectedColor.hex) {
this.setCanvasBackgroundColor(
nextProps.getSelectedColor.hex,
this.state.canvas
);
}
if (nextProps.getSelectedImage.selectedImage) {
this.setCanvasBackground(
nextProps.getSelectedImage.selectedImage,
this.state.canvas
);
}
}
setCanvasBackground = (image, canvas) => {
canvas.setBackgroundImage(image, e => {
canvas.renderAll();
});
};
setCanvasBackgroundColor = (color, canvas) => {
canvas.backgroundImage = 0;
const rgbColor = new fabric.Color(color).toRgb();
canvas.setBackgroundColor(rgbColor.toString(), () => canvas.renderAll());
};
render() {
return (
<div className="image-board">
<canvas
id="canvas"
ref={el => {
this.canvasEl = el;
}}
width={500}
height={400}
className="z-depth-1"
/>
</div>
);
}
}
const mapStateToProps = state => {
return {
getSelectedImage: state.getSelectedImage,
getSelectedColor: state.getSelectedColor
};
};
export default connect(mapStateToProps)(ImageBoard);