Updated springy to latest code.

This commit is contained in:
Dennis Hotson 2010-06-15 21:15:40 +10:00
parent af82e4060b
commit bc489ac33e
7 changed files with 619 additions and 217 deletions

22
LICENSE Executable file
View File

@ -0,0 +1,22 @@
Copyright (c) 2010 Dennis Hotson
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

7
README
View File

@ -1,7 +0,0 @@
Springy - Force directed graph layout algorithm in JavaScript
----
See demo.html for example of usage.
Some proper docs coming soon..

89
README.mkdn Normal file
View File

@ -0,0 +1,89 @@
Springy
====
A force directed graph layout algorithm in JavaScript.
What is this?
----
Springy is a force directed graph layout algorithm.
So what does this 'force directed' stuff mean anyway? Excellent question!
It basically means that it uses some real world physics to try and
figure out how to show a network graph in a nice way.
Try to imagine it as a bunch of springs connected to each other.
Basic Usage
----
springy.js by itself is quite plain and doesn't include any code to do rendering
or drag and drop etc. It's just for calculating the layout.
The drawing and interaction stuff is mostly up to you.
However, I've written a little helper jQuery plugin called springyui.js
to help get you started. It's got a semi-decent default renderer and some
half assed drag and drop.
See demo.html and springyui.js for an example of usage.
Advanced Usage
----
If you're keen to do your own custom drawing, you'll need to know a few
things before you get started.
This is the basic graph API, you can create nodes and edges etc.
// make a new graph
var graph = new Graph();
// make some nodes
var node1 = graph.newNode({label: '1'});
var node2 = graph.newNode({label: '2'});
// connect them with an edge
graph.newEdge(node1, node2);
So now to draw this graph, lets make a layout object:
var layout = new Layout.ForceDirected(graph, 400.0, 400.0, 0.5);
I've written a Renderer class, which will handle the rendering loop.
You just need to provide some callbacks to do the actual drawing.
var renderer = new Renderer(10, layout,
function clear() {
// code to clear screen
},
function drawEdge(edge, p1, p2) {
// draw an edge
},
function drawNode(node, p) {
// draw a node
}
);
Now, just start the rendering loop:
renderer.start();
Further Reading
----
Have a look at the code in springy.js.
Seriously, it's not very much code and it should be pretty easy to understand.
Please let me know if anything is unclear. Feedback is welcome.
Acknowledgements
----
Thanks to [Lachlan Donald](http://github.com/lox) for his helpful suggestions and
feedback.

218
demo.html
View File

@ -1,208 +1,40 @@
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="raphael-min.js"></script>
<script src="springy.js"></script>
<script src="springyui.js"></script>
<script>
var graph = new Graph();
var dennis = graph.newNode({label: 'Dennis'});
var michael = graph.newNode({label: 'Michael'});
var jessica = graph.newNode({label: 'Jessica'});
var timothy = graph.newNode({label: 'Timothy'});
var barbara = graph.newNode({label: 'Barbara'});
var franklin = graph.newNode({label: 'Franklin'});
var monty = graph.newNode({label: 'Monty'});
var james = graph.newNode({label: 'James'});
var bianca = graph.newNode({label: 'Bianca'});
// generate a random graph
graph.newEdge(dennis, michael, {color: '#00A0B0'});
graph.newEdge(michael, dennis, {color: '#6A4A3C'});
graph.newEdge(michael, jessica, {color: '#CC333F'});
graph.newEdge(jessica, barbara, {color: '#EB6841'});
graph.newEdge(michael, timothy, {color: '#EDC951'});
graph.newEdge(franklin, monty, {color: '#7DBE3C'});
graph.newEdge(dennis, monty, {color: '#000000'});
graph.newEdge(monty, james, {color: '#00A0B0'});
graph.newEdge(barbara, timothy, {color: '#6A4A3C'});
graph.newEdge(dennis, bianca, {color: '#CC333F'});
graph.newEdge(bianca, monty, {color: '#EB6841'});
var n = [];
for (var i=0; i<15; i += 1)
{
n[i] = graph.newNode({label: ""+i});
}
for (i=0; i<20; i += 1)
{
var i1 = Math.floor(Math.random() * n.length);
var i2 = i1;
while (i1 === i2) {
i2 = Math.floor(Math.random() * n.length);
}
var n1 = n[i1];
var n2 = n[i2];
var e = graph.newEdge(n1, n2);
var colors = ['#00A0B0', '#6A4A3C', '#CC333F', '#EB6841', '#EDC951', '#7DBE3C'];
e.data.stroke = colors[Math.floor(Math.random() * colors.length)];
}
// -----------
var width = 800;
var height = 600;
var zoom = 40.0;
// convert to/from screen coordinates
toScreen = function(p) {
return new Vector(p.x * zoom + width/2.0, p.y * zoom + height/2.0);
};
fromScreen = function(s) {
return new Vector((s.x - width/2.0) / zoom, (s.y - height/2.0) / zoom);
};
var paper = Raphael(10, 10, width, height);
var layout = new Layout.ForceDirected(graph, 500.0, 300.0, 0.5);
var boxWidth = 30;
var boxHeight = 20;
var renderer = new Renderer(1, layout,
function clear()
{
paper.clear();
var r = paper.rect(0,0,width-1,height-1);
r.attr({"fill": "#FFFFFF", "stroke": "none"});
},
function drawEdge(edge, p1, p2)
{
var x1 = toScreen(p1).x;
var y1 = toScreen(p1).y;
var x2 = toScreen(p2).x;
var y2 = toScreen(p2).y;
var direction = new Vector(x2-x1, y2-y1);
var normal = direction.normal().normalise();
var from = graph.getEdges(edge.source, edge.target);
var to = graph.getEdges(edge.target, edge.source);
var total = from.length + to.length;
var n = from.indexOf(edge);
var spacing = 6.0;
var totalWidth = total * spacing;
// Figure out how far off centre the line should be drawn
var offset = normal.multiply(-((total - 1) * spacing)/2.0 + (n * spacing));
var stroke = typeof(edge.data.stroke) !== 'undefined' ? edge.data.stroke : "#000000";
var s1 = toScreen(p1).add(offset);
var s2 = toScreen(p2).add(offset);
var intersection = intersect_line_box(s1, s2, {x: x2-boxWidth/2.0, y: y2-boxHeight/2.0}, boxWidth, boxHeight);
var c2 = paper.path(["M", s1.x, s1.y, "L", intersection.x, intersection.y]);
c2.attr({stroke: stroke, "stroke-width": 2});
var arrow = paper.path(["M", -7, 4, "L", 0, 0, "L", 7, 0, "L", 0, 0, "L", -7, -4, "L", -5, 0, "z"]);
arrow.rotate(Math.atan2(y2 - y1, x2 - x1) * (180.0 / Math.PI), 0, 0);
arrow.translate(intersection.x, intersection.y);
arrow.attr({fill: stroke, stroke: "none"});
},
function drawNode(node, p)
{
var fill = typeof(node.data.fill) !== 'undefined' ? node.data.fill : "#FFFFFF";
var s = toScreen(p);
var rect = paper.rect(s.x - boxWidth/2.0, s.y - boxHeight/2.0, boxWidth, boxHeight, 4);
rect.attr({fill: fill, "stroke-width": 2});
if (typeof(node.data.label) !== 'undefined')
{
var text = paper.text(s.x, s.y, node.data.label);
text.attr({
"font-family": "Helvetica Neue",
"font-size": "12px",
"font-weight": "bold",
jQuery(document).ready(function(){
jQuery('#springydemo').springy(graph);
});
}
}
);
renderer.start();
// half-assed drag and drop
var selected = null;
jQuery('svg').mousedown(function(e){
var pos = jQuery(this).position();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
selected = layout.nearest(p);
selected.oldm = selected.point.m;
selected.olddata = selected.node.data;
selected.node.data = jQuery.extend(true, {}, selected.node.data); // deep copy
selected.point.m = 1000.0;
selected.node.data.fill = '#EEEEEE';
});
jQuery('svg').mousemove(function(e){
if (selected !== null)
{
var pos = jQuery(this).position();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
selected.point.p.x = p.x;
selected.point.p.y = p.y;
renderer.start();
}
});
jQuery(window).bind('mouseup',function(e){
if (selected !== null)
{
selected.node.data = selected.olddata;
}
selected = null;
});
// helpers for figuring out where to draw arrows
function intersect_line_line(p1, p2, p3, p4)
{
var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));
// lines are parallel
if (denom === 0) {
return false;
}
var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;
if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
return false;
}
return {
x: p1.x + ua * (p2.x - p1.x),
y: p1.y + ua * (p2.y - p1.y)
};
}
function intersect_line_box(p1, p2, p3, w, h)
{
var tl = {x: p3.x, y: p3.y};
var tr = {x: p3.x + w, y: p3.y};
var bl = {x: p3.x, y: p3.y + h};
var br = {x: p3.x + w, y: p3.y + h};
var result;
if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top
if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right
if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom
if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left
return false;
}
</script>
<canvas id="springydemo" width="640" height="480" />
</body>
</html>

7
raphael-min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -1,3 +1,27 @@
/**
Copyright (c) 2010 Dennis Hotson
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
var Graph = function()
{
@ -17,7 +41,6 @@ Node = function(id, data)
this.data = typeof(data) !== 'undefined' ? data : {};
};
Edge = function(id, source, target, data)
{
this.id = id;
@ -27,8 +50,12 @@ Edge = function(id, source, target, data)
};
Graph.prototype.addNode = function(node)
{
if (typeof(this.nodeSet[node.id]) === 'undefined')
{
this.nodes.push(node);
}
this.nodeSet[node.id] = node;
this.notify();
@ -36,19 +63,35 @@ Graph.prototype.addNode = function(node)
};
Graph.prototype.addEdge = function(edge)
{
var exists = false;
this.edges.forEach(function(e){
if (edge.id === e.id) { exists = true; }
});
if (!exists)
{
this.edges.push(edge);
}
if (typeof(this.adjacency[edge.source.id]) === 'undefined')
{
this.adjacency[edge.source.id] = [];
this.adjacency[edge.source.id] = {};
}
if (typeof(this.adjacency[edge.source.id][edge.target.id]) === 'undefined')
{
this.adjacency[edge.source.id][edge.target.id] = [];
}
exists = false;
this.adjacency[edge.source.id][edge.target.id].forEach(function(e){
if (edge.id === e.id) { exists = true; }
});
if (!exists)
{
this.adjacency[edge.source.id][edge.target.id].push(edge);
}
this.notify();
return edge;
@ -80,6 +123,119 @@ Graph.prototype.getEdges = function(node1, node2)
return [];
};
// remove a node and it's associated edges from the graph
Graph.prototype.removeNode = function(node)
{
if (typeof(this.nodeSet[node.id]) !== 'undefined')
{
delete this.nodeSet[node.id];
}
for (var i = this.nodes.length - 1; i >= 0; i--)
{
if (this.nodes[i].id === node.id)
{
this.nodes.splice(i, 1);
}
}
var tmpEdges = this.edges.slice();
tmpEdges.forEach(function(e) {
if (e.source.id === node.id || e.target.id === node.id)
{
this.removeEdge(e);
}
}, this);
this.notify();
};
// remove a node and it's associated edges from the graph
Graph.prototype.removeEdge = function(edge)
{
for (var i = this.edges.length - 1; i >= 0; i--)
{
if (this.edges[i].id === edge.id)
{
this.edges.splice(i, 1);
}
}
for (var x in this.adjacency)
{
for (var y in this.adjacency[x])
{
var edges = this.adjacency[x][y];
for (var j=edges.length - 1; j>=0; j--)
{
if (this.adjacency[x][y][j].id === edge.id)
{
this.adjacency[x][y].splice(j, 1);
}
}
}
}
this.notify();
};
/* Merge a list of nodes and edges into the current graph. eg.
var o = {
nodes: [
{id: 123, data: {type: 'user', userid: 123, displayname: 'aaa'}},
{id: 234, data: {type: 'user', userid: 234, displayname: 'bbb'}}
],
edges: [
{from: 0, to: 1, type: 'submitted_design', directed: true, data: {weight: }}
]
}
*/
Graph.prototype.merge = function(data)
{
var nodes = [];
data.nodes.forEach(function(n) {
nodes.push(graph.addNode(new Node(n.id, n.data)));
}, this);
data.edges.forEach(function(e) {
var from = nodes[e.from];
var to = nodes[e.to];
var id = (e.directed)
? (id = e.type + "-" + from.id + "-" + to.id)
: (from.id < to.id) // normalise id for non-directed edges
? e.type + "-" + from.id + "-" + to.id
: e.type + "-" + to.id + "-" + from.id;
var edge = graph.addEdge(new Edge(id, from, to, e.data));
edge.data.type = e.type;
}, this);
};
Graph.prototype.filterNodes = function(fn)
{
var tmpNodes = this.nodes.slice();
tmpNodes.forEach(function(n) {
if (!fn(n))
{
this.removeNode(n);
}
}, this);
};
Graph.prototype.filterEdges = function(fn)
{
var tmpEdges = this.edges.slice();
tmpEdges.forEach(function(e) {
if (!fn(e))
{
this.removeEdge(e);
}
}, this);
};
Graph.prototype.addGraphListener = function(obj)
{
@ -103,7 +259,7 @@ Layout.ForceDirected = function(graph, stiffness, repulsion, damping)
this.damping = damping; // velocity damping factor
this.nodePoints = {}; // keep track of points associated with nodes
this.edgeSprings = {}; // keep track of points associated with nodes
this.edgeSprings = {}; // keep track of springs associated with edges
this.intervalId = null;
};
@ -221,7 +377,7 @@ Layout.ForceDirected.prototype.attractToCentre = function()
{
this.eachNode(function(node, point) {
var direction = point.p.multiply(-1.0);
point.applyForce(direction.multiply(this.repulsion / 5.0));
point.applyForce(direction.multiply(this.repulsion / 50.0));
});
};
@ -266,8 +422,8 @@ Layout.ForceDirected.prototype.start = function(interval, render, done)
t.applyCoulombsLaw();
t.applyHookesLaw();
t.attractToCentre();
t.updateVelocity(0.04);
t.updatePosition(0.04);
t.updateVelocity(0.03);
t.updatePosition(0.03);
if (typeof(render) !== 'undefined') { render(); }
@ -299,6 +455,33 @@ Layout.ForceDirected.prototype.nearest = function(pos)
return min;
};
// returns [bottomleft, topright]
Layout.ForceDirected.prototype.getBoundingBox = function()
{
var bottomleft = new Vector(-2,-2);
var topright = new Vector(2,2);
this.eachNode(function(n, point) {
if (point.p.x < bottomleft.x) {
bottomleft.x = point.p.x;
}
if (point.p.y < bottomleft.y) {
bottomleft.y = point.p.y;
}
if (point.p.x > topright.x) {
topright.x = point.p.x;
}
if (point.p.y > topright.y) {
topright.y = point.p.y;
}
});
var padding = topright.subtract(bottomleft).multiply(0.07); // 5% padding
return {bottomleft: bottomleft.subtract(padding), topright: topright.add(padding)};
};
// Vector
Vector = function(x, y)
{
@ -308,7 +491,7 @@ Vector = function(x, y)
Vector.random = function()
{
return new Vector(2.0 * (Math.random() - 0.5), 2.0 * (Math.random() - 0.5));
return new Vector(10.0 * (Math.random() - 0.5), 10.0 * (Math.random() - 0.5));
};
Vector.prototype.add = function(v2)

290
springyui.js Executable file
View File

@ -0,0 +1,290 @@
/**
Copyright (c) 2010 Dennis Hotson
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
(function() {
jQuery.fn.springy = function(graph) {
var canvas = this[0];
var ctx = canvas.getContext("2d");
var layout = new Layout.ForceDirected(graph, 400.0, 400.0, 0.5);
// calculate bounding box of graph layout.. with ease-in
var currentBB = layout.getBoundingBox();
var targetBB = {bottomleft: new Vector(-2, -2), topright: new Vector(2, 2)};
// auto adjusting bounding box
setInterval(function(){
targetBB = layout.getBoundingBox();
// current gets 20% closer to target every iteration
currentBB = {
bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft)
.divide(10)),
topright: currentBB.topright.add( targetBB.topright.subtract(currentBB.topright)
.divide(10))
};
}, 50);
// convert to/from screen coordinates
toScreen = function(p) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * canvas.width;
var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * canvas.height;
return new Vector(sx, sy);
};
fromScreen = function(s) {
var size = currentBB.topright.subtract(currentBB.bottomleft);
var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x;
var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y;
return new Vector(px, py);
};
// half-assed drag and drop
var selected = null;
var nearest = null;
var dragged = null;
jQuery(canvas).mousedown(function(e){
jQuery('.actions').hide();
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
selected = nearest = dragged = layout.nearest(p);
if (selected.node !== null)
{
dragged.point.m = 10000.0;
}
renderer.start();
});
jQuery(canvas).mousemove(function(e){
var pos = jQuery(this).offset();
var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
nearest = layout.nearest(p);
if (dragged !== null && dragged.node !== null)
{
dragged.point.p.x = p.x;
dragged.point.p.y = p.y;
}
renderer.start();
});
jQuery(window).bind('mouseup',function(e){
dragged = null;
});
Node.prototype.getWidth = function() {
ctx.save();
var text = typeof(this.data.label) !== 'undefined' ? this.data.label : this.id;
ctx.font = "16px Verdana";
var width = ctx.measureText(text).width + 10;
ctx.restore();
return width;
};
Node.prototype.getHeight = function() {
return 20;
};
var renderer = new Renderer(1, layout,
function clear()
{
ctx.clearRect(0,0,canvas.width,canvas.height);
},
function drawEdge(edge, p1, p2)
{
var x1 = toScreen(p1).x;
var y1 = toScreen(p1).y;
var x2 = toScreen(p2).x;
var y2 = toScreen(p2).y;
var direction = new Vector(x2-x1, y2-y1);
var normal = direction.normal().normalise();
var from = graph.getEdges(edge.source, edge.target);
var to = graph.getEdges(edge.target, edge.source);
var total = from.length + to.length;
var n = 0;
for (var i=0; i<from.length; i++)
{
if (from[i].id === edge.id)
{
n = i;
}
}
var spacing = 6.0;
// Figure out how far off centre the line should be drawn
var offset = normal.multiply(-((total - 1) * spacing)/2.0 + (n * spacing));
var s1 = toScreen(p1).add(offset);
var s2 = toScreen(p2).add(offset);
var boxWidth = edge.target.getWidth();
var boxHeight = edge.target.getHeight();
var intersection = intersect_line_box(s1, s2, {x: x2-boxWidth/2.0, y: y2-boxHeight/2.0}, boxWidth, boxHeight);
if (!intersection) {
intersection = s2;
}
var stroke = typeof(edge.data.color) !== 'undefined' ? edge.data.color : '#000000';
var arrowWidth;
var arrowLength;
var weight = typeof(edge.data.weight) !== 'undefined' ? edge.data.weight : 1.0;
ctx.lineWidth = Math.max(weight * 2, 0.1);
arrowWidth = 1 + ctx.lineWidth;
arrowLength = 8;
var directional = typeof(edge.data.directional) !== 'undefined' ? edge.data.directional : true;
// line
var lineEnd;
if (directional)
{
lineEnd = intersection.subtract(direction.normalise().multiply(arrowLength * 0.5));
}
else
{
lineEnd = s2;
}
ctx.strokeStyle = stroke;
ctx.beginPath();
ctx.moveTo(s1.x, s1.y);
ctx.lineTo(lineEnd.x, lineEnd.y);
ctx.stroke();
// arrow
if (directional)
{
ctx.save();
ctx.fillStyle = stroke;
ctx.translate(intersection.x, intersection.y);
ctx.rotate(Math.atan2(y2 - y1, x2 - x1));
ctx.beginPath();
ctx.moveTo(-arrowLength, arrowWidth);
ctx.lineTo(0, 0);
ctx.lineTo(-arrowLength, -arrowWidth);
ctx.lineTo(-arrowLength * 0.8, -0);
ctx.closePath();
ctx.fill();
ctx.restore();
}
},
function drawNode(node, p)
{
var s = toScreen(p);
ctx.save();
var boxWidth = node.getWidth();
var boxHeight = node.getHeight();
// fill background
ctx.clearRect(s.x - boxWidth/2, s.y - 10, boxWidth, 20);
// fill background
if (selected !== null && nearest.node !== null && selected.node.id === node.id)
{
ctx.fillStyle = "#FFFFE0";
}
else if (nearest !== null && nearest.node !== null && nearest.node.id === node.id)
{
ctx.fillStyle = "#EEEEEE";
}
else
{
ctx.fillStyle = "#FFFFFF";
}
ctx.fillRect(s.x - boxWidth/2, s.y - 10, boxWidth, 20);
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.font = "16px Verdana";
ctx.fillStyle = "#000000";
ctx.font = "16px Verdana";
var text = typeof(node.data.label) !== 'undefined' ? node.data.label : node.id;
ctx.fillText(text, s.x - boxWidth/2 + 5, s.y - 8);
ctx.restore();
}
);
renderer.start();
// helpers for figuring out where to draw arrows
function intersect_line_line(p1, p2, p3, p4)
{
var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));
// lines are parallel
if (denom === 0) {
return false;
}
var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;
if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
return false;
}
return new Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
}
function intersect_line_box(p1, p2, p3, w, h)
{
var tl = {x: p3.x, y: p3.y};
var tr = {x: p3.x + w, y: p3.y};
var bl = {x: p3.x, y: p3.y + h};
var br = {x: p3.x + w, y: p3.y + h};
var result;
if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top
if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right
if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom
if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left
return false;
}
}
})();