JavaScript Graph Library

Dracula.js is a set of tools to display and layout interactive connected graphs and networks, along with various related algorithms from the field of graph theory.

Just plain JavaScript and SVG. The code is released under the MIT license, so commercial use is totally fine.

Creating a graph is simple! You also can customize anything easily.

The code:

var g = new Dracula.Graph();

g.addEdge("strawberry", "cherry");
g.addEdge("strawberry", "apple");
g.addEdge("strawberry", "tomato");

g.addEdge("tomato", "apple");
g.addEdge("tomato", "kiwi");

g.addEdge("cherry", "apple");
g.addEdge("cherry", "kiwi");

var layouter = new Dracula.Layout.Spring(g);
layouter.layout();

var renderer = new Dracula.Renderer.Raphael('canvas', g, 400, 300);
renderer.draw();

The result:

There’s also a copy on cdnjs to use for production:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/graphdracula/1.0.3/dracula.min.js"></script>

Enjoy.

Note: If you are looking for a commercially backed graph drawing software for the browser, take a look at the fantastic library yFiles for HTML! It is the most feature complete graph drawing library available for HTML5 and pleasant to work with.

132 replies on “JavaScript Graph Library”

I did something similar by adding a little to the draw function of edges.
The two points defined by x2, y2, x3, y3 bend the paths towards them. To feather out multiple stacked paths, I added something like this just before var path is defined:

let mul = 1
let c = 0.05
if(redraw_style === 1)
switch(style.edge_count){
case 1:mul+=c;break;
case 2:mul-=c;break;
case 3:mul+=2*c;break;
case 4:mul-=2*c;break;
case 5:mul+=3*c;break;
case 6:mul-=3*c;break;
}
// x2 *= mul;
// x3 *= mul;
y2 *= mul;
y3 *= mul;

A good idea would be passing a JSON object to the class object and it would convert to nodes and edges automatically. Something like this structure

{
“nodes”: [“apple”, “orage”, “banana”, “kiwi”],
“edges”: [{“apple”, “orange”}, {“orange”, “banana”}]
}

I am a new user and I don’t know why the browserify does not work.
I am just following all the instruction to get a demo but it always through a TypeError after I build the bundle using browserify

Awesome project.
How can I vary ‘size’ and ‘shape’ of nodes (keeping common for all but different from the default one provided here) ?

I am a first time user and included the file

https://cdnjs.cloudflare.com/ajax/libs/graphdracula/1.0.3/dracula.min.js

And get this.

Navigated to file:///C:/Users/RPike/SelectFile.html
dracula.min.js:6 Uncaught TypeError: Cannot set property ‘connection’ of undefined
at Object.r.201../renderer (dracula.min.js:6)
at s (dracula.min.js:1)
at dracula.min.js:1
at Object.r.1../src/dracula (dracula.min.js:1)
at s (dracula.min.js:1)
at e (dracula.min.js:1)
at dracula.min.js:1
at dracula.min.js:1
at dracula.min.js:1
r.201../renderer @ dracula.min.js:6
s @ dracula.min.js:1
(anonymous) @ dracula.min.js:1
r.1../src/dracula @ dracula.min.js:1
s @ dracula.min.js:1
e @ dracula.min.js:1
(anonymous) @ dracula.min.js:1
(anonymous) @ dracula.min.js:1
(anonymous) @ dracula.min.js:1

Hi,thanks for providing this program.Could you please tell me how to add a click event on the node that I click on?thanks!

I’m getting the below Script error by using the given script “var g = new Graph(); …..”.
Kindly help me. Do I need to import any Library or need to change any thing.

—- ReferenceError: “Graph” is not defined in at line number 1

Here is my Error generated Code block:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName(“JavaScript”);

// JavaScript code in a String
String script = “function FGenerateGraph()” +
“{” +
“var g = new Graph();” +
“g.addEdge(\”strawberry\”, \”cherry\”);” +
“g.addEdge(\”strawberry\”, \”apple\”);” +
“g.addEdge(\”strawberry\”, \”tomato\”);” +
“” +
“g.addEdge(\”tomato\”, \”apple\”);” +
“g.addEdge(\”tomato\”, \”kiwi\”);” +
“” +
“g.addEdge(\”cherry\”, \”apple\”);” +
“g.addEdge(\”cherry\”, \”kiwi\”);” +
“” +
“var layouter = new Graph.Layout.Spring(g);” +
“layouter.layout();” +
“” +
“var renderer = new Graph.Renderer.Raphael(‘canvas’, g, 400, 300);” +
“renderer.draw();” +
“}”;
// evaluate script
engine.eval(script);

// javax.script.Invocable is an optional interface.
// Check whether your script engine implements or not!
// Note that the JavaScript engine implements Invocable interface.
Invocable inv = (Invocable) engine;

try {
// invoke the global function named “hello”
inv.invokeFunction(“FGenerateGraph”, “Scripting!!” );
} catch (NoSuchMethodException ex) {
Logger.getLogger(GenerateGarphServlet.class.getName()).log(Level.SEVERE, null, ex);
}

Hi,

Great library!
I would like to highlight (= make thinker) the arrows that are connected to the node when dragging. Do you have any suggestions?
Thank you in advance.

Thanks for sharing such a great article
can you please suggest how to Put node name into circle only.

Thanks in advance

Great job simple .but useful
but how could I adjust the length of the edges
and make the node not draggable ?????
I’m writing a paper on Visualization
so I really need those feature…

This is a very useful software … Thank you very much for the effort you’ve done.
I have one question please, can someone include this API in a commercial software that is not open source ?

Regards,

Hi, sorry it took so long: usage of this library in commercial projects or software that is not open soure is totally okay!

Johann,

Is the library still being developed? Latest download is an Alpha from 2012.

Also out of curiosity – is the name of the library “Graph Dracula” intentional 🙂 ? (“Graph” or “Граф” is Russian for “count”)

I still push some code from time to time to GitHub, but it’s currently not stable. I plan to work more on it in the future! The name “Graph” is intentional, since it’s also “Graf” (count) in German 🙂

I posted a patch for the overlapping edges / labels problem but I can’t see it in the comments – is the forum still open?

R

The forum is still open, but I have to go through 100 spam messages for each good one (despite using a spam filter) so things take a while – I promise to be faster in the future 🙂

Great framework, and its very easy to use.

Using this framework how can i implement family tree(child node is derived from two parent nodes)

Thanks in advance

Hey – I’ve modified my version of the code to account for overlapping labels when you have a bidirectional edge. Are you interested in patches?

If someone wants to take it I’ll leave it here:
It works for me – but it needs a small amount of thought before it would handle the ‘general’ case:
Assumptions:
Currently assumes that I can use the node ‘text’ attribute to look up the node in the graph – requires unique node labels
You want size 12 text (or at least 12 pixels between overlapping labels)

      /* setting label */
//find how many overlapping edges there are, use "text" to look up the node
fromNode = g.nodes[obj1[1].attrs["text"]]
toNode = g.nodes[obj2[1].attrs["text"]]
//pick one of the nodes to examine, the one with less connections will me most efficient
examNode = fromNode.edges.length&lt;toNode.edges.length?fromNode:toNode
for(total=0,i=0;i&lt;examNode.edges.length;i++){
//count the number of overlaps
//but keep track of which label we&#039;re actually drawing (&#039;me&#039;)
    if(style.label==examNode.edges[i].style.label){
    me = total+1
    }
//this checks that the edge I&#039;m looking at overlaps me
    if(
        (
        (examNode.edges[i].target.id==toNode.id)&amp;&amp;
        (examNode.edges[i].source.id==fromNode.id)
        )||
        (
        (examNode.edges[i].target.id==fromNode.id)&amp;&amp;
        (examNode.edges[i].source.id==toNode.id)
        )
    )
    {
    total++
//this is the individual pixel offset for that label on that edge
//this calc aims to distribute the labels evenly above and below the mid point
    offset = (me-((total+1)/2))*12 //12 is the pixel spacing
    }
}

/* YOU NOW NEED TO USE YOUR offset IN THE DRAW CODE */

/* Edit the following bit of code lower down to add the &#039;offset&#039;:

(edge.label &amp;&amp; edge.label.attr({x:(x1+x4)/2, y:((y1+y4)/2 + offset) })

*/

very useful lib. I would try porting this to svg.js since it offers fine-grade control over SVG
I already have a half-working prototype using ver. 0.0.3alpha5 of your lib (the trunk ver does not work), is there any chance to collaborate on this? are you continuing work on this?

I will use this in my team to show medical algorithm charts. I can show you some demos (private)

I would like to know that is there a way that two directed edges in opposite direction are drawn without overlapping. Is there already a way to do this? Or is it possible to get the path object of Raphael to customize it?

Thanks in Advance

I have a problem: I have to plot a graph of user attendance etc based on data from database. Can you please tell us which java script library i should use and some sample code would be appreciated.

Hello, I’ve been using this library for a while (June 2013) and I have some questions.
First of all, is it possible to add onclick events on nodes? I saw that others have also asked this but no clear response was given
Also, I tried out the Dijkstra algorithm. My graph is directed and after running some test, I found out that the algorithm simply does not consider the direction of an edge

How can I solve these two issues?

First, Hello to everyone and thanks to share this nice library.
Second: ¿ Im trying to make a circular process, for example: StateA -> StateB->StateC->StateA->StateB … the problem is the arrow between nodes by passing twice shown as if it were just one. Thanks!

roxio easy cd creator 5 platinum probate records centre rubbermaid sheds jafra skin care bradley smoker simmons 22 mag Vertiscapes billiard window blinds czech map [url=http://www.iwcwatchsalejp.com/]IWC 販売[/url]
[url=http://www.viviennejpsale.com/]ヴィヴィアン 店舗[/url]
beach ball needle board swarovski flatback rhinestones hp zd7000 japanese rain chain pinnacle studio 8 se pre calculus for dummies window tint [url=http://www.viviennejpsale.com/]ヴィヴィアン 通販[/url]
cb radio sales gardening tool set psc1350 sante fe railroad recruitment software return address labels roll wet bar powerbook g5

Hi, i have a problem with the library. All the nodes are positioned at the top left. Is there something i m missing ?

thanks

Very good API, thanks man!

I just have a problem: I need to select multiple nodes and move them all together. How should I do that? Also, is it possible rectangle selection of multiple nodes and then move them together?

Thanks in advance for the reply!

I am trying to register a click event on a node but it doesnt seem to be working
g = new Graph();

/* add a simple node */
var strawberry = g.addNode(“strawberry”);

strawberry.click(function()
{
alert(“clicked”);
});
g.addNode(“cherry”);

I tried the click event with the latest code. But its not working
Error:- Uncaught TypeError: Object # has no method ‘onclick’

Ich habe deine coole Library gebraucht, in einer fuer meine Mitbearbeiter und Editoren bestimmten Seite. Jetzt koennen sie ihre Arbeit visuel ueberpruefen, ehe sie losschicken. Ich wuerde gen Dir welche Screenshot zuschicken, wenn du mir deine Email schriebst. Tschuess. Mark.

Hi, Grigory, seems your fork require the Graph has only one root, as a graph, it may has many roots, in this case, the Tree mode won’t work.
I forked your fork, add a Grid mode at https://github.com/ariestiger/dracula-js-fork
But thank you very much, I studied your Tree mode and create Grid mode for myself, though my implementation is very dirty and ugly.

Hi,

this library seem to be the only (free) javascript graph framework with edge labelling. *thumbup*

I tried to implement a dynamic graph, which can add nodes by “onkeyup()”. But the new nodes haven’t been drawn or they are drawn at (0|0). I tried it also with the Fixed layout from Marcelo above, but with the later added nodes it does the same way.
Can somebody help?

Hi. I’m considering integrating dracula graph library into mine raphaeljs porting to GWT (java) http://code.google.com/p/raphael4gwt/. It already contains a full porting of graphael (charts). For my part the requiriment is that dracula uses the last raphaelje version (2.1). As I can see from your sources, it uses an old raphael version 1.3. So have you tried making it to work with rapahel 2? and another question is ¿is jquery a dependency? Regards and congrats for your lib.

Leave a Reply to blues-man Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.