Skip to content

Instantly share code, notes, and snippets.

@HarryStevens
Last active May 19, 2017 13:41
Show Gist options
  • Save HarryStevens/9961d05c8295ec5590d83c55329bb3d0 to your computer and use it in GitHub Desktop.
Save HarryStevens/9961d05c8295ec5590d83c55329bb3d0 to your computer and use it in GitHub Desktop.
Entropy
license: gpl-3.0

Chained transition of a Voronoi diagram. Initial colors based on initial horizontal position.

<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0 auto;
}
</style>
</head>
<body>
<div id="viz"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chroma-js/1.3.3/chroma.min.js"></script>
<script>
var width = window.innerWidth,
height = window.innerHeight,
svg = d3.select("#viz").append("svg")
.attr("width", width)
.attr("height", height)
c = chroma.scale(["white", "steelblue", "white", "black", "white", "tomato", "white"]).mode("hsl"),
x = d3.scaleLinear()
.range([0, width]),
y = d3.scaleLinear()
.range([height, 0]),
voronoi = d3.voronoi()
.x(function(d){ return x(d.x); })
.y(function(d){ return y(d.y); })
.extent([[0, 0], [width, height]]);
var data = generate_data();
redraw(data);
d3.interval(function(){
redraw(update_data(data));
}, 600);
function redraw(data){
x.domain(d3.extent(data, function(d){ return d.x; }));
y.domain(d3.extent(data, function(d){ return d.y; }));
c.domain(d3.extent(data, function(d){ return d.x; }));
var voronoi_path = svg.selectAll(".voronoi")
.data(voronoi(data).polygons(), function(d){ return d == undefined ? null : d.data.id; });
voronoi_path
.transition().delay(function(d, i){ return i / 2; })
.attr("d", function(d) { return d ? "M" + d.join("L") + "Z" : null; });
voronoi_path.enter().append("path")
.attr("class", "voronoi")
.attr("fill", function(d){ return d ? c(d.data.x) : null; })
.attr("d", function(d) { return d ? "M" + d.join("L") + "Z" : null; });
}
function generate_data(){
var arr = [];
for (var i = 0; i<= 250; i++){
arr.push({
id: i,
x: random(0, 1000),
y: random(0, 1000)
});
}
return arr;
}
function update_data(data){
return data.map(function(d){
return {
id: d.id,
x: d.x + random(1, 100),
y: d.y + random(1, 100)
}
});
}
// random number function
function random(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment