Skip to content

Instantly share code, notes, and snippets.

@captainhead
Last active May 21, 2019 01:14
Show Gist options
  • Save captainhead/b542212d5f11e50f2ccaa47a71deb6c7 to your computer and use it in GitHub Desktop.
Save captainhead/b542212d5f11e50f2ccaa47a71deb6c7 to your computer and use it in GitHub Desktop.
A Hexagon symbol for D3
const a = Math.pow(3, 0.25);
// Given an area, compute the side length of a hexagon with that area.
function sideLength(area) {
return a * Math.sqrt(2 * (area / 9));
}
// Generate the 6 vertices of a unit hexagon.
const basePoints = d3
.range(6)
.map(p => (Math.PI / 3) * p)
.map(p => ({
x: Math.cos(p),
y: Math.sin(p)
}));
const hexagonSymbol = {
draw: function (context, size) {
// Scale the unit hexagon's vertices by the desired size of the hexagon.
const len = sideLength(size);
const points = basePoints.map(({x, y}) => ({
x: x * len,
y: y * len
}));
// Move to the first vertex of the hexagon.
let {x, y} = points[0];
context.moveTo(x, y);
// Line-to the remaining vertices of the hexagon.
for (let p = 1; p < points.length; p++) {
let {x, y} = points[p];
context.lineTo(x, y);
}
// Close the path to connect the last vertex back to the first.
context.closePath();
}
};
// export default hexagonSymbol;
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="./hexagon.js"></script>
<!-- <script type="module" src="./hexagon.js"></script> -->
</head>
<body>
<svg width="960" height="500"></svg>
<script>
// import hexagonSymbol from "./hexagon"
const symbolArea = 2900;
const spacing = 100;
const symbol = d3
.symbol()
.size(symbolArea)
.type(hexagonSymbol);
d3.select("svg")
.selectAll("path")
.data([
hexagonSymbol,
d3.symbolSquare,
d3.symbolCircle,
d3.symbolCross,
d3.symbolStar
])
.enter()
.append("path")
.attr("d", d => symbol.type(d)())
.attr(
"transform",
(d, i) => `translate(${spacing / 2 + spacing * i},75)`
)
.attr("stroke-linejoin", "round")
.style("stroke", "lightgreen")
.style("stroke-width", "4px")
.style("fill", "lightgrey");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment