Complete graph creator using Raphael.js

leave a comment »

Complete graph creator

This one is very similar to A Simple Gravity Model except that this one is made with javascript (Raphael.js)  and does not has the gravity model for the width of the links. I made this as a demonstration for how easy it is to make interactive graphics with javascript. With less than 40 lines of code, with raphael and javascript we can create this complete graph generator where you can click the canvas to create nodes and click and drag the nodes to move them. the links are generated and updated based on the position of the nodes. I am planning to create a full suite of tools for making and analysing networks online for which this is the first step. [ link: http://www.bala-ucl.co.uk/jsgraph/index.html ]

Code:

var paper = Raphael(0,0,'100%','100%');
var background = paper.rect(0,0,'100%','100%').attr({'fill':'#ddd','stroke-width':'0'});
var circles = [];
var lines = [];
background.click(function(event){
	circles.push(new circle(event.clientX,event.clientY));
	refreshLines(circles);
});	
function refreshLines(arr) {
	for (i in lines) {
		lines[i].remove();
	}
	for (i in arr) {
		for (j in arr) {
			lines.push(new line(arr[i].attrs.cx,arr[i].attrs.cy,arr[j].attrs.cx,arr[j].attrs.cy));
		}
	}
}
function circle (mx,my) {
	return paper.circle(mx,my,10).attr({fill:'#444',stroke:'#444'}).drag(
		function(da,db,x,y){
			this.attr({cx:x,cy:y});
		},
		function(){
			var color = this.attrs.fill=="#444" ? '#f00' : '#444';
			this.attr({fill:color});
		},
		function(){
			var color = this.attrs.fill=="#444"; ? '#f00' : '#444';
			this.attr({fill:color});
			refreshLines(circles);
		}
	);
}	
function line (sx,sy,ex,ey) {
	return  paper.path( "M"+sx+","+sy+" "+"L"+ex+","+ey ).attr({stroke:'#444'});
}
Advertisements

Written by sbmkvp

November 11, 2014 at 4:43 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: