Skip to content

Instantly share code, notes, and snippets.

@JMStewart
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JMStewart/c5e7eafa751c24d75f0e to your computer and use it in GitHub Desktop.
Save JMStewart/c5e7eafa751c24d75f0e to your computer and use it in GitHub Desktop.
Pure D3 Force

This is a very simple example of a force layout in d3. This is meant to be used as a comparison to the ReactJS + D3 Force example here. Using pure d3 to directly manipulate the DOM is significantly faster that using React.

Also compare to Canvas + D3 Force.

<!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 svg = d3.select('body')
.append('svg')
.attr({
height: height,
width: width
});
var circles = svg.selectAll('circle')
.data(nodes)
.enter()
.append('circle')
.attr('r', function(d){
return d.r;
})
.style({
fill: 'steelblue'
});
force.on('tick', function(){
var renderStart = new Date();
circles.attr({
cx: function(d){
return d.x;
},
cy: function(d){
return d.y;
}
});
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment