我正在尝试创建一个与fabricjs画布进行交互的UI。左侧是一个组件,显示可以添加到画布的项目库。中间将是fabricjs画布,右侧将是一个组件,列出画布上所有添加的项目(类似于photoshops图层面板)。
我想知道如何在左侧组件(ItemsList.js)中创建onClick事件,访问在其父组件中声明的fabricjs画布实例。
这是主要组成部分......
MainComponent.js
import React, { Component } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import ItemsList from './ItemsList.js';
import LayersPanel from './LayersPanel.js';
import {fabric} from 'fabric';
class Designer extends React.Component {
constructor(props) {
super(props);
this.state = {
canvasWidth: ''
};
}
updateCanvasDimensions() {
this.setState({
canvasWidth: this.refs.canvas_wrapper.offsetWidth
});
canvas.setHeight(this.state.canvasWidth);
canvas.setWidth(this.state.canvasWidth);
}
componentDidMount() {
canvas = new fabric.Canvas('c', {
width: this.refs.canvas_wrapper.offsetWidth,
height: this.refs.canvas_wrapper.offsetWidth
});
this.updateCanvasDimensions(canvas);
window.addEventListener("resize", this.updateCanvasDimensions.bind(this));
canvas.renderAll();
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateCanvasDimensions.bind(this));
}
render() {
return (
<div>
<div>
<ItemsList />
</div>
<div className="canvas-wrapper" ref="canvas_wrapper">
<canvas ref="c" id = "c"></canvas>
</div>
<div>
<LayersPanel />
</div>
</div>
);
}
}
export default createContainer(({ params }) => {
return {
};
}, Designer);
在ItemsList.js中的某个位置,对于列表中的每个项目,都有一个按钮可将项目的图像添加到画布。
...
<Button onClick={() => {
//Need to get the canvas instance here so
//that I can add this particular item's image to the canvas like this...
canvas.add(rowData.image);
}}>Add Item</Button>
...
单击ItemsList组件中特定项目的此按钮后,我希望将单击的项目图像添加到树中组件中声明的画布。例如......
<MainComponent> <-- This is where I declare the fabric canvas.
<ItemsList>
<Item/> <-- This is where the button is clicked.
</ItemsList>
</MainComponent>
如何从<Item/>
?
如果它与答案相关,同时我还需要右侧的组件(<LayersPanel/>
)来显示添加到画布的内容。
由于
答案 0 :(得分:0)
我已成功完成以下操作......
创建画布......
<canvas ref="c" id = "c"></canvas>
从任何地方挑选(只要它已加载了)...
canvas = document.getElementById("c").fabric;