<canvas id="canvas" width="1000" height="1000"></canvas>
<script>
    const ctx = document.getElementById("canvas").getContext('2d');

    /** 最初の始点 */
    const X = 1000;
    const Y = 1000;

    /** 最初の辺長 */
    const LENGTH = 1000;

    // 最初の三角形を描画
    function drawIniTriangle() {
        ctx.beginPath();
        ctx.moveTo(X, Y);
        ctx.lineTo(X - LENGTH, Y);
        ctx.lineTo(X - LENGTH / 2, Y - LENGTH * 3 ** 0.5 / 2);
        ctx.closePath();
        ctx.strokeStyle = "black";
        ctx.stroke();
    }
    drawIniTriangle();

    // k=1の場合の、始点を求める
    function calcKeyPoint(x, y, l) {
        return [{
            x: x - l / 4,
            y: y - l * 3 ** 0.5 / 4
        }]
    }

    // k>=2の場合の、始点を求める
    function calcKeyPoints(x, y, l) {
        return [{
            x: x - l / 4,
            y: y - l * 3 ** 0.5 / 4
        }, {
            x: x + l / 4,
            y: y + l * 3 ** 0.5 / 4
        }, {
            x: x - l * 3 / 4,
            y: y + l * 3 ** 0.5 / 4
        }]
    }

    // 始点から下向き正三角形を描画
    function drawTriangle(x, y, l) {
        ctx.beginPath();
        ctx.moveTo(x, y);
        ctx.lineTo(x - l, y);
        ctx.lineTo(x - l / 2, y + l * 3 ** 0.5 / 2);
        ctx.closePath();
        ctx.strokeStyle = "black";
        ctx.stroke();
    }

    // k=1の下向き正三角形を描画 始点が1つ
    let point = calcKeyPoint(X, Y, LENGTH);
    point.forEach(v => drawTriangle(v.x, v.y, LENGTH / 2));

    // 前回の始点、辺長を保持
    let beforePoints = point;
    let beforeLength = LENGTH / 2;

    // k>=2の下向き正三角形を描画
    function drawFrame() {
        if (beforeLength < 10) {
            clearInterval(id);
            console.log('end')
        }
        let points = beforePoints.reduce((v, w) => {
            return v.concat(calcKeyPoints(w.x, w.y, beforeLength));
        }, []);
        points.forEach(v => drawTriangle(v.x, v.y, beforeLength / 2));
        beforePoints = points;
        beforeLength /= 2;
    }
    // requestAnimationFrameのほうがよいが、今回は簡易的なものなので省略
    let id = setInterval(drawFrame, 1000);
</script>
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.