Skip to content

Instantly share code, notes, and snippets.

@Kcnarf
Last active December 3, 2018 08:30
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Kcnarf/6d5ace3aa9cc1a313d72b810388d1003 to your computer and use it in GitHub Desktop.
Voronoi-based point picker (revisited)
license: gpl-3.0
<html>
<head>
<script type="text/javascript" src="https://d3js.org/d3.v4.js"></script>
<script src="https://raw.githack.com/Kcnarf/d3-distanceLimitedVoronoi/master/distance-limited-voronoi.js"></script>
</head>
<body>
<div id="chart">
</div>
<div id="slider" style="position:absolute; top:0px">
Interactive zone radius :
<form>
<input id="limit" type="range" name="points" min="0" max="100" value="20" oninput="redraw()">
</form>
</div>
<script type="text/javascript">
var w = 960,
h = 500;
var vertices = d3.range(100).map(function(d) {
return [Math.random() * w, Math.random() * h];
});
var svg = d3.select("#chart")
.append("svg:svg")
.attr("width", w)
.attr("height", h);
var paths, points;
points = svg.append("svg:g").attr("id", "points");
paths = svg.append("svg:g").attr("id", "point-paths");
var limitedVoronoi = d3.distanceLimitedVoronoi();
var limit;
var redraw = function () {
limit = +d3.select("#limit").node().value;
if (limit===+d3.select("#limit").node().max) { limit = Infinity; }
limitedVoronoi.limit(limit);
var path = paths.selectAll("path")
.data(limitedVoronoi(vertices));
path = path.enter().append("svg:path").merge(path);
path.attr("d", function(d) { return d.path; })
.attr("id", function(d,i) {
return "path-"+i; })
.style("fill", d3.rgb(230, 230, 230))
.style('fill-opacity', 0.4)
.style("stroke", d3.rgb(200,200,200))
.on("mouseover", function(d, i) {
d3.select(this)
.style('fill', d3.rgb(31, 120, 180));
svg.select('circle#point-'+i)
.style('fill', d3.rgb(31, 120, 180))
})
.on("mouseout", function(d, i) {
d3.select(this)
.style("fill", d3.rgb(230, 230, 230));
svg.select('circle#point-'+i)
.style('fill', 'black')
});
points.selectAll("circle")
.data(vertices)
.enter().append("svg:circle")
.attr("id", function(d, i) {
return "point-"+i; })
.attr("transform", function(d) { return "translate(" + d + ")"; })
.attr("r", 2)
.attr('stroke', 'none');
}
redraw()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment