Skip to content

Instantly share code, notes, and snippets.

@DavidBruant
Last active May 28, 2016 19:28
Show Gist options
  • Save DavidBruant/6489486 to your computer and use it in GitHub Desktop.
Save DavidBruant/6489486 to your computer and use it in GitHub Desktop.
Breaking down attribute moves in d3 to fit in requestAnimationFrame
var moveItems = (function(){
var todoNode = 0;
var todoLink = 0;
var MAX_NODES = 240;
var MAX_LINKS = MAX_NODES/2;
var restart = false;
function moveSomeNodes(){
var n;
var goal = Math.min(todoNode+MAX_NODES, node[0].length);
for(var i=todoNode ; i < goal ; i++){
n = node[0][i];
n.setAttribute('cx', n.__data__.x);
n.setAttribute('cy', n.__data__.y);
}
todoNode = goal;
requestAnimationFrame(moveSome)
}
function moveSomeLinks(){
var l;
var goal = Math.min(todoLink+MAX_LINKS, link[0].length);
for(var i=todoLink ; i < goal ; i++){
l = link[0][i];
//console.log(l);
l.setAttribute('x1', l.__data__.source.x);
l.setAttribute('y1', l.__data__.source.y);
l.setAttribute('x2', l.__data__.target.x);
l.setAttribute('y2', l.__data__.target.y);
}
todoLink = goal;
requestAnimationFrame(moveSome)
}
function moveSome(){
//console.time('moveSome')
if(todoNode < node[0].length) // some more nodes to do
moveSomeNodes()
else{ // nodes are done
if(todoLink < link[0].length) // some more links to do
moveSomeLinks()
else{ // both nodes and links are done
if(restart){
restart = false;
todoNode = 0;
todoLink = 0;
requestAnimationFrame(moveSome);
}
}
}
//console.timeEnd('moveSome')
}
return function moveItems(){
if(!restart){
restart = true;
requestAnimationFrame(moveSome);
}
};
})();
force.on('tick', function tick() {
/*link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });*/
moveItems();
});
@DavidBruant
Copy link
Author

When the graph reaches ~300 edges, changing all edges attributes makes the graph lag. This code moves only at requestAnimationFrame making the animation smooth all the time, regardless of the number of edges.

@bishop335
Copy link

That is very good of you man

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment