I am trying to create a UI to interact with a fabricjs canvas. On the left will be a component that displays a library of items that can be added to the canvas. In the middle will be the fabricjs canvas, and on the right will be a component that lists all the added items that are on the canvas (similar to photoshops layers panel).
I want to know how I can have an onClick event within the component on the left (ItemsList.js), access the fabricjs canvas instance that is declared in it's parent component.
This is the main component...
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);
Somewhere within ItemsList.js, for each item on the list, there is a button to add the item's image to the canvas.
...
<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>
...
After this button is clicked for a particular item in the ItemsList component, I want the clicked item's image to be added to the canvas that is declared in a components up the tree. For example...
<MainComponent> <-- This is where I declare the fabric canvas.
<ItemsList>
<Item/> <-- This is where the button is clicked.
</ItemsList>
</MainComponent>
How can I access the canvas instance from within <Item/>?
In case it's relevant to the answer, at the same time, I also need the component on the right (<LayersPanel/>) to display what is added to the canvas.
Thanks