This is the code for Chapter 1, Figure 34 from D3.js in Action that creates various SVG elements and then animates them using D3 transitions.
forked from emeeks's block: Ch. 1, Fig. 34 - D3.js in Action
xxxxxxxxxx
<html lang="en">
<head>
<meta charset="utf-8">
<title>AN Scratchpad</title>
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script type="text/javascript">
var w = 960;
var h = 500;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var block_width = 10;
var block_height = 10;
var block_stroke = 2;
var block_pad = 2;
var layoutw = 10;
var layouth = 10;
var dispx = 5;
var dispy = 5;
for (i = 0; i < layoutw; i++) {
layout1[i] += [i,j];
}
/*
var layout1 = [
[0,0],[1,0],[2,0],[3,0],[4,0],
[0,1],[1,1],[2,1],[3,1],[4,1],
[0,2],[1,2],[2,2],[3,2],[4,2],
[0,3],[1,3],[2,3],[3,3],[4,3],
[0,4],[1,4],[2,4],[3,4],[4,4],
[0,5],[1,5],[2,5],[3,5],[4,5],
];
*/
svg.selectAll("rect")
.data(layout1)
.enter()
.append("rect")
.attr("y", 20)
.attr("stroke","grey")
.attr("stroke-width",block_stroke)
.attr("fill","white")
.attr("width", block_width)
.attr("height", block_height)
.attr("x", function(d) {
return 40 + d[0] * (block_width + (block_stroke / 2) + block_pad);
})
.attr("y", function(d) {
return h - 40 - d[1] * (block_width + (block_stroke / 2) + block_pad);
});
//svg.selectAll("rect").transition().duration(1000).attr("y", 200).attr("x",200);
d3.selectAll("rect")
.on("click", function() {
layout1.forEach(function(i){
console.log(i);
i[0]=i[0]+dispx;
i[1]=i[1]+dispy;
});
svg.selectAll("rect")
.data(layout1)
.transition()
.duration(500)
.delay(function(d, i) { return i * 100; })
.attr("x", function(d) {
return 40 + d[0] * (block_width + (block_stroke / 2) + block_pad);
})
.attr("y", function(d) {
return h - 40 - d[1] * (block_width + (block_stroke / 2) + block_pad);
})
});
</script>
</body>
</html>
https://d3js.org/d3.v4.min.js