Skip to content

Instantly share code, notes, and snippets.

@saifuddin778
Last active June 25, 2016 06:03
Show Gist options
  • Save saifuddin778/99ab84ee74713b1be55bbec0d8adfe47 to your computer and use it in GitHub Desktop.
Save saifuddin778/99ab84ee74713b1be55bbec0d8adfe47 to your computer and use it in GitHub Desktop.
Polygon Transition

D3 transitions on polygons. A polygon is any shape with more than 2 set of coordinates geometrically bounded to form a shape. D3 does have a higher level implementation of tweening shapes and polygons, but this example demonstrates a lower level way of manipulating polygon coordinates.

<!DOCTYPE html>
<meta charset="utf-8">
<style></style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var width = 960;
var height = 503;
function rb(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function get_polygon_points(points) {
var pts = "";
for (var i = 0; i < points.length; i++) {
for (var j = 0; j < points[i].length; j++) {
if (i < points.length - 1) {
pts += points[i][j] + " ";
} else {
pts += points[i][j] + " ";
}
}
pts += " "
}
return pts;
}
function get_ppoints(bds) {
var pcorners = 30;
var xq = pad_x * 0.01;
var yq = pad_y * 0.01;
bds.min_x = bds.min_x + xq;
bds.max_x = bds.max_x - xq;
bds.min_y = bds.min_y - yq;
bds.max_y = bds.max_y + yq;
var ppoints = d3.range(pcorners)
.map(function (d, i) {
return [rb(bds.min_x, bds.max_x), rb(bds.min_y, bds.max_y)];
});
return get_polygon_points(ppoints);
}
var space = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var n = 9;
var m = n * n;
var pad_x = width / n;
var pad_y = height / n;
var x = 0;
var y = 0 - pad_y;
var nodes = d3.range(m)
.map(function (d, i) {
x = pad_x * (d % n);
if (d % n == 0) {
y += pad_y;
}
return {
x: x,
y: y,
width: pad_x,
height: pad_y,
}
});
var colors = d3.scale.linear()
.interpolate(d3.interpolateHcl)
.domain([0, m])
.range(['cornflowerblue', 'crimson']);
space.selectAll(".nodes")
.data(nodes)
.enter()
.append("polygon")
.attr("class", "polys")
.each(function (d, i) {
var bounds = {
min_x: d.x,
max_x: d.x + pad_x,
min_y: d.y,
max_y: d.y + pad_y,
};
d3.select(this)
.attr("points", get_ppoints(bounds))
.style("fill", colors(Math.random() * m - rb(Math.random() * i, m)))
});
space.on("mouseover", function () {
d3.selectAll(".polys")
.transition()
.duration(500)
.attr("points", function (d, i) {
var bounds = {
min_x: d.x,
max_x: d.x + pad_x,
min_y: d.y,
max_y: d.y + pad_y,
};
return get_ppoints(bounds);
})
.style("fill", function (d, i) {
return colors(Math.random() * m - rb(Math.random() * i, m))
});
d3.event.stopPropagation();
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment