简体   繁体   中英

D3.js Transition issue

I am learning D3.js and it seems quite easy, well.. so far until this transition came up.

I want to make the rectangle bars animate their width , but all they are doing is the color is changing.

I can't quite understand what i am doing wrong.

Here's my JavaScript

var dataArray = [20, 30, 40, 60];
dataArray2 = [20, 40, 60];
dataPosition = [0, 300, 600];
width = 500;
height = 500;

var widthScale = d3.scale.linear()
    .domain([0, 60])
    .range([0, width]);

var axis = d3.svg.axis()
    .ticks(5)
    .scale(widthScale);

var colorScale = d3.scale.linear()
    .domain([0, 60])
    .range(["hsl(" + Math.random() * 360 + ",100%,50%)", "hsl(" + Math.random() * 360 + ",100%,50%)"]);

var canvas = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(20,0)");


var bars = canvas.selectAll("rect")
    .data(dataArray)
    .enter().append("rect")
    .transition()
    .duration(1500)
    .attr("width", function (d) {
    return widthScale(d);
})
    .attr("height", 50)
    .attr("fill", function (d) {
    return colorScale(d);
})
    .attr("y", function (d, i) {
    return i * 100;
})


canvas.append("g")
    .call(axis)
    .attr("transform", "translate(0,400)");

My fiddle

Is it also possible for numbers to be iterated on the rectangles along the way?

You gotta first set the value to zero, then add the transition code the delay time and then the finally set the actual value

http://jsfiddle.net/M8TXZ/1/

var bars = canvas.selectAll("rect")
   .data(dataArray)
   .enter().append("rect")
   .transition()
   .duration(1500)
   .attr("height", 50)
   .attr("fill", function(d) {
      return colorScale(d);
   })
   .attr("y", function(d, i) {
      return i * 100;
   })
   //Sets the width to zero
   .attr("width", function(d) {
      return 0;
   })
   .transition()
   .duration(1000)
   //Sets the width to the actual value
   .attr("width", function(d) {
      return widthScale(d);
   })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM