Skip to content

Instantly share code, notes, and snippets.

@bencates
Created June 26, 2014 04:43
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bencates/5b490ed79796cbd35863 to your computer and use it in GitHub Desktop.
Save bencates/5b490ed79796cbd35863 to your computer and use it in GitHub Desktop.
Draw a SVG hexagonal grid
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>SVG Test</title>
</head>
<body>
<svg id="s" version="1.1"
width="300" height="300"
xmlns="http://www.w3.org/2000/svg">
</svg>
<script>
function hexPoints(x, y, radius) {
var points = [];
for (var theta = 0; theta < Math.PI * 2; theta += Math.PI / 3) {
var pointX, pointY;
pointX = x + radius * Math.sin(theta);
pointY = y + radius * Math.cos(theta);
points.push(pointX + ',' + pointY);
}
return points.join(' ');
}
var x, y, row, col, pointX, pointY, theta;
var svg = document.getElementById('s');
var radius = 30;
for (col = 0; col < 4; col += 1) {
for (row = 0; row < 4; row += 1) {
var offset = (Math.sqrt(3) * radius) / 2;
x = 40 + offset * col * 2;
y = 40 + offset * row * Math.sqrt(3);
if (row % 2 !== 0) x += offset;
var polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.style.fill = 'white';
polygon.style.stroke = 'black';
polygon.style.strokeWidth = '4px';
polygon.setAttribute('points', hexPoints(x, y, radius));
polygon.addEventListener('click', function (event) {
event.target.style.boxShadow = '0 0 5px blue inset';
}, false);
svg.appendChild(polygon);
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment