samedi 27 décembre 2014

How to draw a dragable Voronoi Delaunay triangulation geom in d3.js


Using d3.js I have been able to setup a simple Voronoi geom with draggable polygons:



// define width and height of svg element
var w = 500,
h = 500;

// generate some random data points
var vertices = d3.range(50).map(function(d) {
return [Math.random() * w, Math.random() * h];
});

// setup voronoi geom
var voronoi = d3.geom.voronoi().x(function(d) { return d.x; }).y(function(d) { return d.y; });

// not sure why but removing this breaks drag functionality
var zoom = d3.behavior.zoom().on("zoom", function(d,i) {
force.nodes(vertices).start();
});

// prepare svg element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
.call(zoom);

// setup the force
var force = d3.layout.force()
.charge(-800)
.size([w, h])
.on("tick", update)
.nodes(vertices)
.start();

// setup the path
var path = svg.selectAll("path");

// make it happen
function update(e) {
path = path.data(voronoi(vertices))
.attr("d", function(d) { return "M" + d.join("L") + "Z"; });

path.enter().append("path")
.call(d3.behavior.drag()
.on("drag", function(d, i) {
vertices[i] = {x: vertices[i].x + d3.event.dx, y: vertices[i].y + d3.event.dy};
})
);
}


jsfiddle


How can this code be modified to use the triangles method to draw draggable triangles instead of mixed polygons?


Modifying path = path.data(voronoi(vertices)) to path = path.data(voronoi.triangles(vertices)) on line 38 just makes a mess.





Aucun commentaire:

Enregistrer un commentaire