This is an example of redering a d3.js force directed graph onto an HTML5 canvas.
Compare to Pure D3 Force and ReactJS + D3 Force.
Also compare an alternative method using custom-namespaced DOM elements here.
This is an example of redering a d3.js force directed graph onto an HTML5 canvas.
Compare to Pure D3 Force and ReactJS + D3 Force.
Also compare an alternative method using custom-namespaced DOM elements here.
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
</head> | |
<body> | |
<script> | |
var size = 1000; | |
var height = 500; | |
var width = 960; | |
var charge = -0.3; | |
var data = d3.range(size).map(function(){ | |
return {r: Math.floor(Math.random() * 8 + 2)}; | |
}); | |
var start = new Date(); | |
var time = 0; | |
var ticks = 0; | |
var force = d3.layout.force() | |
.size([width, height]) | |
.nodes(data) | |
.charge(function(d){ | |
return d.r * d.r * charge; | |
}) | |
.start(); | |
var nodes = force.nodes(); | |
var canvas = d3.select('body') | |
.append('canvas') | |
.attr({ | |
height: height, | |
width: width | |
}); | |
var context = canvas.node().getContext("2d"); | |
force.on('tick', function(){ | |
var renderStart = new Date(); | |
context.clearRect(0, 0, width, height); | |
context.fillStyle = "steelblue"; | |
context.beginPath(); | |
nodes.forEach(function(d) { | |
context.moveTo(d.x, d.y); | |
context.arc(d.x, d.y, d.r, 0, 2 * Math.PI); | |
}); | |
context.fill(); | |
time += (new Date() - renderStart); | |
ticks++; | |
}); | |
force.on('end', function(){ | |
var totalTime = new Date() - start; | |
console.log('Total Time:', totalTime); | |
console.log('Render Time:', time); | |
console.log('Ticks:', ticks); | |
console.log('Average Time:', totalTime / ticks); | |
}); | |
</script> | |
</html> |