Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a circle into a square with d3.js

After appending 25 circles to the page, I run the following function:

var transitionPage = function () {
  startThePage();
  var height = $(document).height() - 20
    , width = $(document).width()
    ;

  d3.selectAll("circle")
    .transition().duration(2500)
      .style("fill", "steelblue")
      .attr("r", 15)
    .transition().duration(1000)
      .attr("cy", (height / 2))
    .each(function (d, i) {
      d3.select(this)
        .transition().duration(1000)
        .attr("cx", 30 + (i * width / 25));
    });
}

This works well and correctly lines them up horizontally along the middle of the page.

However, I couldn't figure out how to then transform each circle into a square or rectangle.

How should I approach this problem?

like image 623
royhowie Avatar asked Jul 02 '13 23:07

royhowie


People also ask

Is D3 js easy?

D3. js is easy to use.

What is stroke in D3?

The stroke-linejoin style specifies the shape of the join of two lines. This would be used on path , polyline and polygon elements (and possibly more).

What is SVG in D3?

SVG stands for Scalable Vector Graphics. SVG is an XML-based vector graphics format. It provides options to draw different shapes such as Lines, Rectangles, Circles, Ellipses, etc. Hence, designing visualizations with SVG gives you more power and flexibility.


1 Answers

In the svg recomendation there are no transformation possible for the circle shape to become a square. What you can try to do, and if you have control over this part, is to draw squares instead of circles and apply a border radius on it. Something like this:

d3.select("body").select("svg").append("rect")
    .attr("rx",100)
    .attr("ry",100)
    .attr("x",100)
    .attr("y",100)
    .attr("width",100)
    .attr("height",100)
    .attr("stroke","black")
    .attr("fill","white");

Then the transition from a circle to a square could be done as:

d3.select("rect")
    .transition()
    .duration(1000)
    .attr("rx",0)
    .attr("ry",0);
like image 151
user688877 Avatar answered Oct 05 '22 23:10

user688877