I am starting to work on an application using preact, and I would like to know if it is possible to use FabricJS in preact. Can someone help me understand how I can do this?
Asked
Active
Viewed 344 times
0
-
1So if preact is a version of react, then yes. Just do not try to bind fabricjs objects to react components, to me it does not makes sense – AndreaBogazzi Jul 19 '17 at 10:10
-
Possible duplicate of [How can I use Fabric.js with React?](https://stackoverflow.com/questions/37565041/how-can-i-use-fabric-js-with-react) – btzr Jul 28 '17 at 18:03
2 Answers
0
Basic example
To do that, place your Fabric instantiation into componentDidMount
@RishatMuhametshin
import { Component } from 'preact';
import { findDOMNode } from 'preact-compat';
class MyComponent extends Component {
componentDidMount() {
const self = findDOMNode(this); // Or just the canvas ID
const canvas = new fabric.Canvas();
// fabric initialize...
canvas.initialize(self, { /* Canvas options */ });
}
render() {
return ( <canvas id="myCanvas" /> )
}
}
Global example
//Somewhere else
const canvas = new fabric.Canvas();
// MyComponent.js
class MyComponent extends Component {
componentDidMount() {
//Initialize fabric js
canvas.initialize("myCanvasId", { /* Canvas options */ });
// fabric js stuff...
const square = new canvas.Rect({
fill: 'red',
width: 50,
height: 50
});
//Add object
canvas.add(square);
}
render() {
return (
<div class={"myComponentClass"}>
{ /* your component content... */ }
<canvas id="myCanvasId" />
</div>
)
}
}
You should check: How can I use fabric-js with react?

btzr
- 2,077
- 18
- 25