Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

reactjs - How can I use Fabric.js with React?

I have an application using heavily HTML5 canvas via Fabric.js. The app is written on top of Angular 1.x, and I am planning to migrate it to React. My app allows writing text and drawing lines, rectangles, and ellipses. It is also possible to move, enlarge, shrink, select, cut, copy, and paste one or more of such objects. It is also possible to zoom and pan the canvas using various shortcuts. In short, my app utilizes Fabric.js to its full extent.

I couldn't find much information on how to use Fabric.js together with React, so my concern is that 1. is it possible without major modifications, and 2. does it make sense or should I instead use some other extensive canvas library that has better support for React?

The only example of React+Fabric.js I could find, was react-komik, which however is much more simpler than my app. My main concerns are the event processing and DOM manipulation of Fabric.js, and their effect on React.

There seems to be also a canvas library for React, called react-canvas, but it seems lacking a lot of features compared to Fabric.js.

What do I have to take into account (regarding DOM manipulation, event processing, etc.) when using Fabric.js in a React app?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We had this same issue in our app of how to use Fabric.js inside of react. My recommendation is to treat fabric as an uncontrolled component. Have fabric instance that your whole app can talk to and make fabric calls and then when anything changes use .toObject() call to put the whole fabric state into your Redux store. Then your React app can read fabric state from your global Redux state as you would do in any normal React app.

I can't get an example working in the StackOverflow code editor but here is a JSFiddle example that implements the pattern I am recommending.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...