Skip to content

Instantly share code, notes, and snippets.

@kevinfjbecker
Created December 27, 2011 22:45
Show Gist options
  • Save kevinfjbecker/1525393 to your computer and use it in GitHub Desktop.
Save kevinfjbecker/1525393 to your computer and use it in GitHub Desktop.
HTML5 Canvas Graph View
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>graph-vis</title>
</head>
<body>
<canvas id="viewer" width="800" height="500"></canvas>
<script src="graph-vis.js"></script>
</body>
</html>
var graph = {
nodelist: [{
x: 25,
y: 25
}, {
x: 75,
y: 25
}, {
x: 125,
y: 75
}, {
x: 75,
y: 125
}, {
x: 25,
y: 125
}],
edgelist: [{
n: 0,
m: 1
}, {
n: 0,
m: 4
}, {
n: 1,
m: 2
}, {
n: 1,
m: 3
}, {
n: 1,
m: 4
}, {
n: 2,
m: 3
}, {
n: 3,
m: 4
}]
};
graph.draw = function(ctx) {
var i;
var n, m;
for(i = 0; i < this.edgelist.length; i += 1) {
n = this.nodelist[this.edgelist[i].n];
m = this.nodelist[this.edgelist[i].m];
drawEdge(ctx, n.x, n.y, m.x, m.y);
}
for(i = 0; i < this.nodelist.length; i += 1) {
n = this.nodelist[i];
drawNode(ctx, n.x, n.y);
}
};
var drawNode = function(ctx, x, y) {
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(x,y,10,0,Math.PI*2,true);
ctx.fill();
ctx.stroke();
};
var drawEdge = function(ctx, x0, y0, x1, y1) {
ctx.beginPath();
ctx.moveTo(x0,y0);
ctx.lineTo(x1,y1);
ctx.stroke();
};
(function draw() {
var canvas = document.getElementById("viewer");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
graph.draw(ctx);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment