Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responding to tick events during d3 transitions

I have an svg line element which points to an svg rectangle element. When the rectangle moves, the line needs to follow it. Is there a way to do this when the rectangle is moved with a d3 transition? I'm looking for something that allows me to respond to each tick of the rectangle's transition. An analogous thing is provided for force layout simulations:

force.on("tick", function() {
  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; });

  node.attr("cx", function(d) { return d.x; })
     .attr("cy", function(d) { return d.y; });

});

This can be used to move two elements at each step in time. Can it be done for arbitrary transitions in the absence of a layout? It seems like transition.each() could do this if it could listen for a transition tick event, but it can only listen for transition start and end events.

I don't want to set a separate transition on the line element because I need to guarantee that the two elements move completely concurrently.

like image 467
pvans Avatar asked Oct 02 '22 10:10

pvans


2 Answers

There's no tick event for transitions, so you can't do exactly what you want. There should be no need for this however -- you can simply add a transition to the line end in the same way as to the rectangle. The code would look something like this.

rect.transition().attr("x", newX).attr("y", newY);
line.transition().attr("x2", newX).attr("y2", newY);
like image 130
Lars Kotthoff Avatar answered Oct 13 '22 11:10

Lars Kotthoff


The method for invoking a function at each tick of a transition is transition.tween().

You pass a name and a factory function. The name is just an identifier. The factory function is called once for each element in the transition, and should return a function to be called on that element for each tick.

like image 29
Robin Houston Avatar answered Oct 13 '22 11:10

Robin Houston