Skip to content

Instantly share code, notes, and snippets.

@akollegger
Last active September 11, 2017 01:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akollegger/4acc769a83e1d8f596bfd9670b58d5b3 to your computer and use it in GitHub Desktop.
Save akollegger/4acc769a83e1d8f596bfd9670b58d5b3 to your computer and use it in GitHub Desktop.
Honeycomb
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/honeycomb-grid@0.6.1/dist/honeycomb.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
html,
body {
height: 100%;
margin: 0;
color: #333;
font-family: sans-serif;
overflow: hidden;
}
#container {
display: block;
position: relative;
width: 960px;
height: 600px;
margin: 0 auto;
background-color: #ccc;
overflow: hidden;
}
svg polygon {
fill: #69c;
stroke: #036;
stroke-width: 0.5;
}
svg polygon:hover {
stroke: #fff;
}
svg text {
fill: #036;
text-anchor: middle;
}
</style>
</head>
<body>
<svg id="container"></svg>
<script>
var Grid = Honeycomb.Grid,
View = Honeycomb.View,
Point = Honeycomb.Point,
container = document.getElementById('container'),
rect = container.getBoundingClientRect(),
grid,
view
grid = Grid({ size: 40, orientation: Honeycomb.HEX_ORIENTATIONS.FLAT })
view = View({
grid: grid,
template: function createTemplate(hex) {
var NS = 'http://www.w3.org/2000/svg',
position = this.hexToPixel(hex),
hexCenter = hex.topLeft().multiply(-1),
g = document.createElementNS(NS, 'g'),
polygon = document.createElementNS(NS, 'polygon'),
text = document.createElementNS(NS, 'text'),
textValue = document.createTextNode(`${hex.x}, ${hex.y}, ${hex.z}`),
points = hex.corners().map(corner => corner.x + ',' + corner.y).join(' ')
polygon.setAttribute('points', points)
text.setAttribute('x', hexCenter.x)
text.setAttribute('y', hexCenter.y)
text.appendChild(textValue)
g.appendChild(polygon)
g.appendChild(text)
g.setAttribute('transform', 'translate(' + position.x + ',' + position.y + ')')
return g
},
container: container,
origin: {
x: rect.width / 2,
y: rect.height / 2
}
})
console.log('view', view)
const padding = 3;
const hexWidth = view.width() + padding;
const hexHeight = view.height() + padding;
view.renderHexes(grid.rectangle({
width: hexWidth, height: hexHeight,
direction: 1,
start: Point(Math.round(0 - hexWidth/2), 0)
}));
// Honeycomb.View will have helpers for handling events in the future
container.addEventListener('click', function handleClick(e) {
// e.offsetX/Y isn't supported by firefox, so calculating it here:
var offsetX = e.clientX - rect.left,
offsetY = e.clientY - rect.top,
hex = view.pixelToHex([offsetX, offsetY])
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment