Transitioning between SVG shapes (circle to rectangle)

5,361 views
Skip to first unread message

Alex Simoes

unread,
Sep 27, 2011, 12:04:41 PM9/27/11
to d3-js
I realize that it is possible to transition the attributes of an SVG
node e.g. the fill, stroke, opacity etc but is it possible to
transition the actual shape itself i.e. from say a circle to a
rectangle?

Mike Bostock

unread,
Sep 27, 2011, 12:10:15 PM9/27/11
to d3...@googlegroups.com
> is it possible to transition the actual shape itself i.e. from say a
> circle to a rectangle?

Yes, but not automatically. You either need to write a custom
interpolator (e.g., attrTween) or use a polygon with many intermediate
points. An example of the latter approach is here:

http://bl.ocks.org/1020902

For a custom interpolator, you'd probably use SVG's elliptical arc
path commands, describing a rectangle with four arc segments. These
arc segments would have a very large radius, making them nearly
straight. Then, you'd interpolate to a circle consisting of the same
four arc segments, with the radius of each arc equal to the radius of
the circle. You could also use Bézier curves to approximate this
(which would allow the rectangle to be perfectly straight, but the
circle would only be approximate).

Mike

Alex Simoes

unread,
Sep 27, 2011, 12:48:24 PM9/27/11
to d3-js
Mike,

Thank you very much, I ended up using your superfomula code, packaging
that function into an external file and calling that to transition
between my shapes. For anyone else with this problem, here's what my
code looks like:

<script src="d3.js"></script>
<script src="d3.superformula.js"></script>
<script>
var svg = d3.select("body").append("svg:svg");

var square = superformula()
.type("square")
.size(100000)
.segments(3600);

var circle = superformula()
.type("circle")
.size(100000)
.segments(3600);

var path = svg.append("svg:path")
.attr("transform", "translate(480,250)")
.attr("d", circle)
.transition().duration(1500)
.attr("d", square);
</script>

The superformula function can be found at this URL: http://bl.ocks.org/1021103.

- alex

Chris Viau

unread,
Sep 27, 2011, 2:05:39 PM9/27/11
to d3...@googlegroups.com
For the circle to rectangle tweening specifically, you could use the rounded corners attributes rx and ry. You can also write custom superformula shapes if you want You can play with the variables here: http://bl.ocks.org/1021103
Reply all
Reply to author
Forward
0 new messages