【发布时间】:2019-06-26 03:25:27
【问题描述】:
我正在使用带有 reactjs 的 Fabric js 将文本添加到画布。添加了文本,但是当我尝试清除字符或选定的单词时,整个文本都会被清除。我看到了一些与此相关的资源,但我使用的是 reactjs,所以很难为我解决这个问题。这是我的做法
class ImageBoard extends React.Component {
constructor() {
super();
this.state = {
selected: undefined
};
}
handleDeleteKey = event => {
if (event.keyCode === 46 || event.keyCode === 8) {
event.preventDefault();
if (this.state.selected !== undefined) {
this.canvas.remove(this.state.selected);
this.setState({ selected: undefined });
}
}
};
componentDidMount() {
this.canvas = new fabric.Canvas("canvas");
document.addEventListener("keydown", this.handleDeleteKey, false);
this.canvas.on("object:selected", e =>
this.setState({ selected: e.target })
);
this.canvas.on("selection:cleared", e =>
this.setState({ selected: undefined })
);
this.canvas.setBackgroundColor(
"rgba(255, 73, 64, 0.6)",
this.canvas.renderAll.bind(this.canvas)
);
}
componentDidUpdate(prevProps) {
if (prevProps.images !== this.props.images) {
this.setCanvasBackground(this.props.images, this.canvas);
}
}
addText = () => {
let text = new fabric.IText("Double click me to change the text!", {
fontSize: 28,
fontWeight: 600,
left: 100,
top: 100,
fill: "black",
width: 20,
height: 20
});
this.canvas.add(text);
};
render() {
return (
<Wrapper>
<Column width={80}>
<canvas
id="canvas"
ref={el => (this.canvasEl = el)}
width={580}
height={400}
className="z-depth-1"
/>
</Column>
<Filter
addText={this.addText}
/>
</Wrapper>
);
}
}
export default connect(mapStateToProps)(ImageBoard);
【问题讨论】:
标签: javascript reactjs fabricjs