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
504 views
in Technique[技术] by (71.8m points)

javascript - How to use Fabric.js to do Visio like drawings with connections?

I've recently started to use Fabric.js for a project and it's great. It provides an abstraction layer for the canvas, and has an entire 'object manipulation layer/mask' that accompanies each object.

I'd like to take it a step further and leverage it to make actual diagrams, with connections between objects, as well as have more 'metadata' that accompanies each object. Has anyone already done this already? Is Fabric.js the right choice for this?

Any thoughts on how I would approach creating 'connector' objects between two objects that respond to events from the objects they're attached to?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's possible in fabricjs - in fact I've made something similar, but much simpler.

In my project I needed to implement an editable line, but not a Fabric built-in line, which is editable by a bounding box, but the line that will allow you to drag one of its ends, like in every vector drawing application.

It seems to be impossible with just one object, so I ended up creating three objects - one line and two small circles at the ends. Then I set up the references from line to circles and from circles to line - this way I can find all objects attached to the object I'm currently moving.

Now, during every object move I check if the object have any references to attached line/circle and if it has - I need to run special line-moving code that will update all attached objects.

Demo:

You can find simple tech-demo here: www.drawee.kolenda.me/techdemo.

Just click "Line", drag your mouse in a frame, click "Edit" - and you can see line dragging at work. You can drag the line itself, or one of its ends.

-

In your specific situation you'll probably want to disable selection or dragging of your connections, you may also want to update connection shape, so it's some kind of a dynamic curve, instead of a straight line, but I think that the core functionality will be the same.

Metadata:

If you want to add some additional data it can't be simpler - every JS object is a dictionary, that stores key-value pairs, so you just need to add another key-value pair to the object. Just keep in mind that JS and Fabric uses some key names internally, so keep your key names different than what you already have. My custom key names in this demo were "line", "circle1" and "circle2" - you may find them in the source code.


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

...