Skip to content

Instantly share code, notes, and snippets.

@takehiko
Last active December 7, 2023 13:25
Show Gist options
  • Save takehiko/f4e2e881612a4fd6f0eb229f3a4a9152 to your computer and use it in GitHub Desktop.
Save takehiko/f4e2e881612a4fd6f0eb229f3a4a9152 to your computer and use it in GitHub Desktop.
Hexagon triangles: you can click triangles to change the color.
Display the source blob
Display the rendered blob
Raw
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" width="355" height="288" id="dominationgame">
<defs>
<style type="text/css"><![CDATA[
#bg { fill:#cfc; stroke:none; }
.t0 { stroke:black; stroke-width:2px; }
.t1 { fill:white; }
]]></style>
</defs>
<rect x="0" y="0" width="355" height="288" id="bg"/>
<g id="rects">
</g>
<script><![CDATA[
function addHexagonTriangles(xo = 100, yo = 100, side = 80, debugPrint = false) {
const g = document.getElementById('rects');
for (let i = 0; i < 6; i++) {
const x1 = xo + side * Math.sin(Math.PI * 2 / 6 * i);
const y1 = yo + side * Math.cos(Math.PI * 2 / 6 * i);
const x2 = xo + side * Math.sin(Math.PI * 2 / 6 * (i + 1));
const y2 = yo + side * Math.cos(Math.PI * 2 / 6 * (i + 1));
const s = document.createElementNS('http://www.w3.org/2000/svg', 'path');
s.setAttribute('d', `M ${xo},${yo} L ${x1},${y1} ${x2},${y2} z`);
s.setAttribute('class', 't0 t1');
if (debugPrint) console.log(s);
g.appendChild(s);
}
}
const side = 80;
const height2 = side * Math.sin(Math.PI / 3);
const margin = 4;
// const imageWidth = Math.ceil(margin * 2 + height2 * 5);
// const imageHeight = Math.ceil(margin * 2 + side * 3.5);
// console.log([imageWidth, imageHeight]); // [355, 288]
addHexagonTriangles(margin + height2 * 2, margin + side, side, false);
addHexagonTriangles(margin + height2 * 4, margin + side, side, false);
addHexagonTriangles(margin + height2, margin + side * 2.5, side, false);
addHexagonTriangles(margin + height2 * 3, margin + side * 2.5, side, false);
function enableToChangeColor(debugPrint = false) {
const r = document.getElementById('rects').children;
for (let i = 0; i < r.length; i++) {
if (r[i].classList.contains('t1')) {
r[i].style.fill = 'white';
r[i].onclick = function () {
const currentColor = this.style.fill;
if (debugPrint) console.log(currentColor);
const colorList = ["white", "blue", "green", "red", "yellow", "purple", "silver"];
let j;
for (j = 0; j < colorList.length; j++) {
if (currentColor == colorList[j])
break;
}
if (j >= colorList.length - 1)
j = -1;
j++;
this.style.fill = colorList[j];
}
}
}
}
enableToChangeColor();
]]></script>
</svg>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment