Playing around with HTML5 canvas to draw a triangles grid
Here is the full code for this prototype, I was trying to find a simple way to draw this grid, and then I’ve converted it to work in Unity 3D with meshes and more fun stuff !
Of course this script is far from being optimized, it was only a quick test to validate some ideas.
Result:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas
id="myCanvas"
width="500"
height="500"
style="border: 1px solid black"
>
</canvas>
<script>
var points = [
[
[0, 0],
[0.5, 0.5],
[1, 0],
],
[
[0, 1],
[1, 1],
[0.5, 0.5],
],
[
[0, 0],
[0.5, 0.5],
[0, 1],
],
[
[1, 0],
[0.5, 0.5],
[1, 1],
],
[
[0, 1],
[0.5, 1.5],
[1, 1],
],
[
[0, 2],
[1, 2],
[0.5, 1.5],
],
[
[0, 1],
[0.5, 1.5],
[0, 2],
],
[
[1, 1],
[0.5, 1.5],
[1, 2],
],
[
[0, 2],
[0.5, 2.5],
[1, 2],
],
[
[0, 3],
[1, 3],
[0.5, 2.5],
],
[
[0, 2],
[0.5, 2.5],
[0, 3],
],
[
[1, 2],
[0.5, 2.5],
[1, 3],
],
[
[1, 0],
[1.5, 0.5],
[2, 0],
],
[
[1, 1],
[2, 1],
[1.5, 0.5],
],
[
[1, 0],
[1.5, 0.5],
[1, 1],
],
[
[2, 0],
[1.5, 0.5],
[2, 1],
],
[
[1, 1],
[1.5, 1.5],
[2, 1],
],
[
[1, 2],
[2, 2],
[1.5, 1.5],
],
[
[1, 1],
[1.5, 1.5],
[1, 2],
],
[
[2, 1],
[1.5, 1.5],
[2, 2],
],
[
[1, 2],
[1.5, 2.5],
[2, 2],
],
[
[1, 3],
[2, 3],
[1.5, 2.5],
],
[
[1, 2],
[1.5, 2.5],
[1, 3],
],
[
[2, 2],
[1.5, 2.5],
[2, 3],
],
[
[2, 0],
[2.5, 0.5],
[3, 0],
],
[
[2, 1],
[3, 1],
[2.5, 0.5],
],
[
[2, 0],
[2.5, 0.5],
[2, 1],
],
[
[3, 0],
[2.5, 0.5],
[3, 1],
],
[
[2, 1],
[2.5, 1.5],
[3, 1],
],
[
[2, 2],
[3, 2],
[2.5, 1.5],
],
[
[2, 1],
[2.5, 1.5],
[2, 2],
],
[
[3, 1],
[2.5, 1.5],
[3, 2],
],
[
[2, 2],
[2.5, 2.5],
[3, 2],
],
[
[2, 3],
[3, 3],
[2.5, 2.5],
],
[
[2, 2],
[2.5, 2.5],
[2, 3],
],
[
[3, 2],
[2.5, 2.5],
[3, 3],
],
];
console.log(points.length);
var ctx = document.getElementById("myCanvas").getContext("2d");
var scale = 50;
var offset = 10;
points.forEach((point) => {
let old = null;
let start = null;
point.forEach((p, key) => {
if (!old)
start = [p[0] * 2 * scale + offset, p[1] * 2 * scale + offset];
ctx.beginPath();
ctx.moveTo(p[0] * 2 * scale + offset, p[1] * 2 * scale + offset);
if (old) {
ctx.lineTo(...[...old]);
ctx.stroke();
}
old = [p[0] * 2 * scale + offset, p[1] * 2 * scale + offset];
if (key === point.length - 1) {
ctx.moveTo(...[...start]);
ctx.lineTo(...[...old]);
ctx.stroke();
}
});
});
</script>
</body>
</html>