コッホ曲線

コッホ曲線を描いてみました

<html>
<body>
<canvas id="koch" height=600px width=800px></canvas>
<script>
window.onload = function() {
var canvas = document.getElementById("koch");
var ctx = canvas.getContext("2d");

function drawKoch(stack, x, y, s, L) {
    if(L <= 1) {
        ctx.moveTo(x, y);
        ctx.lineTo(x + L*Math.cos(s),
                   y - L*Math.sin(s));
    } else {
        d = [
            [2*L/3, 0, 0],
            [L/2, -Math.sqrt(3)/6*L, -Math.PI/3],
            [L/3, 0, Math.PI/3],
            [0, 0, 0]
        ];
        for(var i=0;i<4;++i) {
            var dx = d[i][0];
            var dy = d[i][1];
            var dx1 = Math.cos(s) * dx + Math.sin(s) * dy;
            var dy1 = -Math.sin(s) * dx + Math.cos(s) * dy;
            stack.push([x + dx1, y + dy1, s + d[i][2], L/3]);
	}
    } 
}

stack = [
    [0, 400, 0, 800],
];

ctx.beginPath();
ctx.moveTo(300, 300);
while(stack.length > 0) {
    var args = [stack].concat(stack.pop());
    drawKoch.apply(this, args);
}
ctx.stroke();
}

</script>
</body>
</html>