Monday, March 25, 2013

Hacking arbor.js


Arborjs is one of the best graph visualization libraries available. It can be used to render in different ways such as  HTML5 canvas, HTML elements or SVG. Arborjs is build using web workers and jQuery. Arborjs uses physics engine for processing. You can find more details about it here.

Defining nodes, edges and redrawing is obvious if you go through Arborjs documentation. Therefore I am not going to explain about those. If you render Arborjs to canvas, it will become responsive. You will be able interact with nodes. Nodes will have a repulsion and gravity. Both are achieved by using physics engine. But when you click and hold a particular point on the canvas, it will lock the nearest node. But desirable behavior would be, it should lock down the node under the mouse pointer. If there is no node under mouse pointer, any of the nodes should not get locked.

In order to achieve this, we can use the selected pixel color and compare with canvas background color. If click is on top of a node, then pixel will have a different color than canvas background color. By using canvas click event, you can retrieve pixel coordinates. With those pixel coordinates, by comparing shapes and their sizes we can identify under which node that pixel falls. Then we can retrieve clicked node object which can be used in many applications.To implement this, all the required mathematical functions are described in Arborjs documentation.

Another hack is to create edges dynamically by colliding nodes to each other. When you click down the mouse, you can get the nearest node by using nearest() method in arbor.js. Then without releasing the mouse, you drag the node and struck it into another node. And then you release the mouse. Thereafter when you call nearest() for mouse release event, you will retrieve the next node which you struck your holding node. But that's wrong. Because  nearest() will always give you the holding node instead of struck node. Therefore you need to create another function called nearestNext(). Following is an implementation for that function. You can add this right after nearest() in arbor.js.
This method will basically compare and skip the current holding node and get the next nearest node. Therefore this will return the struck node.