Skip to content

Instantly share code, notes, and snippets.

@sabha
Created October 27, 2021 18:01
Show Gist options
  • Save sabha/5d4c27a6ad68e6a5c63b05a820166260 to your computer and use it in GitHub Desktop.
Save sabha/5d4c27a6ad68e6a5c63b05a820166260 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Triangle</title>
<style>
canvas {
border: solid 1px;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
window.onload = function () {
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let r = false;
let c = 0;
const line = (p1, p2) => {
if (r) {
c = Math.random() * 10;
ctx.beginPath();
ctx.moveTo(p1.x, p1.y + c);
ctx.lineTo(p2.x + c, p2.y);
ctx.stroke();
return;
}
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
};
const mid = (v1, v2) => ({
x: (v1.x + v2.x) / 2,
y: (v1.y + v2.y) / 2,
});
const tringle = (v1, v2, v3) => {
line(v1, v2);
line(v2, v3);
line(v3, v1);
};
function rec(n, v1, v2, v3, tris = [], path = "") {
if (n >= 5) {
return;
}
console.log(n, path);
if (n === 4) tris.push({ v1, v2, v3 });
//tringle(v1, v2, v3);
const m1 = mid(v1, v2);
const m2 = mid(v2, v3);
const m3 = mid(v3, v1);
rec(n + 1, v1, m1, m3, tris, path + "-" + n);
rec(n + 1, m1, m2, v2, tris, path + "-" + n);
rec(n + 1, m2, v3, m3, tris, path + "-" + n);
return tris;
}
const v1 = { x: 50, y: 450 };
const v2 = { x: 450, y: 450 };
const v3 = { x: mid(v1, v2).x, y: 50 };
const Tris = rec(0, v1, v2, v3, [], "START");
let index = 0;
r = true;
[1, 2, 3].forEach((i) => {
Tris.forEach(({ v1, v2, v3 }) => {
tringle(v1, v2, v3);
});
});
};
</script>
</body>
</html>
@sabha
Copy link
Author

sabha commented Oct 27, 2021

Screen Shot 2021-10-27 at 12 59 56 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment