Skip to content

Instantly share code, notes, and snippets.

@cpietsch

cpietsch/README.md

Last active Jan 4, 2016
Embed
What would you like to do?
Voronoi Images

Using voronoi tessellation on random points as a surface for images. From here you could distribute the points in a more meaningfull way e.g. using t-SNE or d3.layout.force()

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = 960,
height = 500;
var vertices = d3.range(100).map(function(d) {
return [Math.random() * width, Math.random() * height];
});
var voronoi = d3.geom.voronoi()
.clipExtent([[0, 0], [width, height]]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
var clip = svg.append("g").selectAll("clipPath");
var image = svg.append("g").selectAll("image");
var flickrApi = "https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=ab8509e656e68cbf711c216c0208cfe4&format=json&nojsoncallback=1";
d3.json(flickrApi, function(data){
console.log("flickrApi", data);
var imgs = data.photos.photo.map(function(d){
return "https://farm"+ d.farm +".staticflickr.com/"+ d.server +"/"+ d.id +"_"+ d.secret +"_m.jpg";
})
render(imgs);
})
function render(imgs) {
voro = voronoi(vertices).map(d3.geom.polygon);
clip.data(voro, polygon).enter().append("clipPath")
.attr("id", function(d,i){ return "clip"+i; })
.append("path")
.attr("d", polygon)
image.data(voro, polygon).enter().append("image")
.style("opacity",0)
.attr("width", 240)
.attr("height", 180)
.attr("x", function(d){ return d.centroid()[0]-120; })
.attr("y", function(d){ return d.centroid()[1]-90; })
.attr("xlink:href", function(d,i){ return imgs[i] })
.attr("clip-path", function(d,i) { return "url(#clip"+i+")"; })
.on("load", function(d){
d3.select(this).transition().style("opacity",1)
})
}
function polygon(d) {
return "M" + d.join("L") + "Z";
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.