Skip to content

Instantly share code, notes, and snippets.

@SuzanaK
Forked from mbostock/.block
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SuzanaK/9e3dd897738514d7b948 to your computer and use it in GitHub Desktop.
Save SuzanaK/9e3dd897738514d7b948 to your computer and use it in GitHub Desktop.
Color grid example of d3.js animated transformations

D3 2.5.0 supports matrix decomposition for animating 2D transforms. Any SVG transform attribute is decomposed into a canonical representation of translate, rotate, scale and skew. This allows two arbitrary transforms of different types to be transitioned smoothly—say from a simple translate to a scale plus rotate. These features are supported automatically by your browser for CSS3 transitions, but now you can have them in JavaScript for SVG, too!

<!DOCTYPE html>
<meta charset="utf-8">
<title>Transform Transitions</title>
<style>
body {
margin: 0;
}
rect {
stroke: #fff;
stroke-width: .1px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var w = 960,
h = 500,
z = 20,
x = w / z,
y = h / z;
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(d3.range(x * y))
.enter().append("rect")
.attr("transform", translate)
.attr("width", z)
.attr("height", z)
.style("fill", function(d) { return d3.hsl(d % x / x * 360, 1, Math.floor(d / x) / y); })
.on("mouseover", mouseover);
function translate(d) {
return "translate(" + (d % x) * z + "," + Math.floor(d / x) * z + ")";
}
function mouseover(d) {
this.parentNode.appendChild(this);
d3.select(this)
.style("pointer-events", "none")
.transition()
.duration(750)
.attr("transform", "translate(480,480)scale(23)rotate(180)")
.transition()
.delay(1500)
.attr("transform", "translate(240,240)scale(0)")
.style("fill-opacity", 0)
.remove();
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment