BrianTGT
BrianTGT

Reputation: 3

D3 Animating a Graph onLoad of page

I'm trying to animate my d3 graphs on load of the page from left to right using maybe the elastic tween but I am somewhat new to d3 and trying to learn so I am sure this is very simple but I can't seem to find a good example to help me with this. I have attached the html and the json if needed to help.

Also curious if somebody knows how to apply a border radius effect to the right side of each bar to curve the edges?

  <html>


   <head>
   <script src="http://d3js.org/d3.v3.min.js"></script>

   <style>
    .canvas {background: #03ff01;
      height: 30em;
      width:70em;
      float: left;
      position: absolute;
      z-index:-1;
     }

     svg {padding-top:3em;
      stroke:black;
      stroke-width:1;
      shape-rendering: crispEdges;}

  </style>
  </head>

  <body>
  <div class = "canvas">
  <script>

  d3.json("mydata2.json", function(data){

    var fill = d3.scale.category10();

    var canvas = d3.select("body").append("svg")
      .attr("width", 1000)
      .attr("height", 1000)

      canvas.selectAll("rect")
      .data(data)
      .enter()
        .append("rect")
        .attr("width", function (d) { return d.amount * 10; })
        .attr("height", 46)
        .attr("y", function (d, i) {return i * 50;})
        .style("fill", function(d, i) { return fill(i); })


        canvas.selectAll("text")
          .data(data)
          .enter()
              .append("text")
              .style("font-family", "Impact")
              .style("font-size", function(d) { return d.size + "px"; })
              .attr("fill", "White")
              .attr("x", function (d, i) {return i + 10; })
              .attr("y", function (d, i) {return i * 50 + 28; })
              .text (function (d) {return d.name +": $" +d.amount;})


     })
   </script>
   </div>
   </body>
   </html>


   //JSON FILE CODE
   mydata2.json
   [
     {"name": "Maria", "amount": 30},
     {"name": "Fred", "amount": 50},
     {"name": "Francis", "amount": 12},
     {"name": "Gerry", "amount": 68},
     {"name": "Tony", "amount": 90}
   ]

Upvotes: 0

Views: 2304

Answers (1)

mdml
mdml

Reputation: 22882

Here's a very simple example you can play around with:

canvas.selectAll("rect")
    .attr("width", 0)
    .transition()
    .delay(function(d, i){ return i*50; })
    .duration(1000)
    .attr("width", function (d) { return d.amount * 10; })

It works by first setting the width of all the <rect>s to 0, and then creating an animation lasting 1 second (1000 milliseconds) to expand each of them to their full width. There's also a slight delay, so that the transition for the <rect>s don't all happen at the same time.

Note that -- just like in this SO question -- you must set the width of each <rect> to 0 before performing the transition, so D3 has a starting value for the animation.

Upvotes: 1

Related Questions