Last active
November 20, 2017 18:40
-
-
Save limscoder/ff7a5079b3b371fb9de5583bfd9d1de9 to your computer and use it in GitHub Desktop.
Draw a grid of hexagons
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// defines a path for a single hexagon. | |
const h = Math.sqrt(3) / 2; | |
const r = 30; | |
const x = 0; | |
const y = 0; | |
const hexPath = d3.line() | |
.x(d => d.x) | |
.y(d => d.y) | |
.curve(d3.curveCardinalClosed.tension('0.8'))([ | |
{ x: r + x, y }, | |
{ x: r / 2 + x, y: r * h + y }, | |
{ x: -r / 2 + x, y: r * h + y }, | |
{ x: -r + x, y }, | |
{ x: -r / 2 + x, y: -r * h + y }, | |
{ x: r / 2 + x, y: -r * h + y } | |
]); | |
// returns an array representing a grid of hexagons | |
function hexData(cols = 7, rows = 7) { | |
const hexes = []; | |
const centerCol = Math.floor(cols / 2); | |
const centerRow = Math.floor(rows / 2); | |
for (let i = 0; i < cols; i++) { | |
for (let j = 0; j < rows; j++) { | |
hexes.push({ | |
active: i === centerCol && j === centerRow, | |
col: i, | |
row: j | |
}); | |
} | |
} | |
return hexes; | |
} | |
// draw hexagons to existing DOM element using d3 data selection API | |
d3.select('svg.hex-container') | |
.selectAll('.hex') | |
.data(hexData()) | |
.enter() | |
.append('path') | |
.attr('class', 'hex') | |
.attr('d', hexPath) | |
.attr('fill', 'grey') | |
.attr('stroke', 'transparent') | |
.attr('stroke-width', 4) | |
.attr('transform', d => { | |
// move each hexagon to its position in the grid | |
// using "col" and "row" properties of each datum | |
const cx = (d.col * r * 2) + (d.row % 2 ? r * 2 : r); | |
const cy = (d.row * r * 1.75) + r; | |
return `translate(${cx}, ${cy}) rotate(90 0 0)`; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment