raghu
raghu

Reputation: 389

Transition functionality in d3js

I was trying to move objects with a defined final state- needed help to provide final state... It does work when I provide the end state x position as attr("cx",function(d,i){return(i*100)+25;}) . I want to be able to define the x and y positions in end-state in an array. e.g. xposition=[50, 100, 200,300, 550]; yposition=[100, 200, 300,400,500] or from a json (x,y) feed

How do I go about that? Thanks

    <!DOCTYPE html>
  <html lang="en">
<head>
    <meta charset="utf-8">
    <title>D3 Test</title>
    <script type="text/javascript" src="d3/d3.v3.js"></script>
</head>
<body>
    <script type="text/javascript">
var svg=d3.select("body").append("svg").attr("height",500).attr
("width",800);
var dataset =[5,10,15,20,25];
var xposition=[50,100,150,400,800];
var h=100;
var circles= svg.selectAll("circle").data(dataset).enter().append("circle");
circles.attr("cx",function(d,i){return (i*50)+25;}).attr("cy",h/2).attr("r",function(d){return d;});

circles.transition().attr("cx",function(d,i){return(i*100)+25;}).attr("cy",4*h).attr("r",function(d){return 2*d;}).delay(1000).duration(1000).ease("cubic");

Upvotes: 1

Views: 50

Answers (2)

Nayan Mehta
Nayan Mehta

Reputation: 9

For example:

The attr operator is built on top of the attrTween operator. The tween function used by the attr operator depends on whether the end value is a function or a constant.

If the end value is a function:

function tween(d, i, a) {
  return d3.interpolate(a, String(value.call(this, d, i)));
}

Otherwise, if the end value is a constant:

function tween(d, i, a) {
  return d3.interpolate(a, String(value));
}

Upvotes: 0

Gerardo Furtado
Gerardo Furtado

Reputation: 102219

Right now, as they are both arrays, you only need to reference xposition and yposition by the index in your function(d, i):

circles.transition()
    .attr("cx",function(d,i){return xposition[i]})
    .attr("cy",function(d,i){return yposition[i]})
    .attr("r",function(d){return 2*d;})
    .delay(1000)
    .duration(1000)
    .ease("cubic");

This is the fiddle: https://jsfiddle.net/gerardofurtado/m8hnas3e/

But let me tell you that this is not the "D3 way" of dealing with data. D3 offer you powerful set of tools to manipulate elements based on data, you really should use it. If you have a JSON, as you said in your question, you could simply bind the data and do every transition and manipulation you want.

Upvotes: 1

Related Questions