Skip to content

Instantly share code, notes, and snippets.

@Anupheaus
Last active June 20, 2017 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Anupheaus/f79c12c2cec45caa9dfd1e6466663ef2 to your computer and use it in GitHub Desktop.
Save Anupheaus/f79c12c2cec45caa9dfd1e6466663ef2 to your computer and use it in GitHub Desktop.
d3 v3 hull bug
<html>
<head>
<style type="text/css">
path {
stroke: #000;
stroke-width: .5px;
fill: #39c;
}
circle {
fill: #39c;
}
.hull {
stroke: #E0E0E0;
fill: #E0E0E0;
stroke-width: 0;
stroke-linejoin: round;
transition-duration: 400ms;
transition-property: opacity, stroke-width;
opacity: 1;
}
</style>
<script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>
</head>
<body>
<svg></svg>
<script type="text/javascript">
const w = 800;
const h = 600;
const points = [[120, 120], [500, 200]];
const circleRadius = 100;
const svg = d3.select("svg")
.attr("width", w)
.attr("height", h);
const hullCanvas = svg.append("g");
const circles = svg.append("g");
const curve = d3.svg.line()
.interpolate("basis-closed")
.tension(1);
function convertPointsForHull(points) {
return points
.map(function (point) {
const slices = 36;
const anglePerSlice = (Math.PI * 2) / slices;
const hullPoints = [];
let radius = circleRadius + 10;
for (let slice = 0; slice < slices; slice++) {
const angle = slice * anglePerSlice;
const x = point[0] + (radius * Math.cos(angle));
const y = point[1] + (radius * Math.sin(angle));
hullPoints.push([x, y]);
}
return hullPoints;
})
.reduce((list, points) => list.concat(points), []);
}
circles
.selectAll("circle")
.data(points)
.enter()
.append("circle")
.attr("r", circleRadius)
.attr("cx", function (d) { return d[0]; })
.attr("cy", function (d) { return d[1]; });
const hullPoints = convertPointsForHull(points);
const hull = hullCanvas
.append('path')
.classed('hull', true);
function setHull(points) {
const allPoints = convertPointsForHull(points);
hull
.datum(d3.geom.hull(allPoints))
.transition()
.duration(3000)
.attr("d", curve);
}
setHull([points[0]]);
setTimeout(() => {
setHull(points);
}, 1000);
hullCanvas
.selectAll("circle")
.data(hullPoints)
.enter()
.append("circle")
.attr("r", 1)
.attr("cx", function (d) { return d[0]; })
.attr("cy", function (d) { return d[1]; });
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment