LoginSignup
0
0

More than 3 years have passed since last update.

コッホ曲線 JavaScript

Last updated at Posted at 2020-01-26
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <script>
        var ctx;

        function init() {
            var canvas = document.getElementById('main_canvas');
            if (!canvas || !canvas.getContext) {
                return;
            }
            ctx = canvas.getContext('2d');

            var N = 3;
            Koch(0, 260, 150, 0, N);
            Koch(150, 0, 300, 260, N);
            Koch(300, 260, 0, 260, N);
        }

        function Koch(ox, oy, rx, ry, n) {
            var dx = rx - ox;
            var dy = ry - oy;

            var px = ox + dx / 3;
            var py = oy + dy / 3;
            var qx = ox + dx / 3 * 2;
            var qy = oy + dy / 3 * 2;

            var distance = Math.sqrt(dx * dx + dy * dy) / Math.sqrt(3);
            var radian;
            var sx;
            var sy;
            if (dx >= 0) {
                radian = Math.atan(-dy / dx) + Math.PI / 6;
                sx = ox + distance * Math.cos(radian);
                sy = oy - distance * Math.sin(radian);
            } else {
                radian = Math.atan(-dy / dx) - Math.PI / 6;
                sx = rx + distance * Math.cos(radian);
                sy = ry - distance * Math.sin(radian);
            }

            if (n == 0) {
                draw(ox, oy, px, py);
                draw(px, py, sx, sy);
                draw(sx, sy, qx, qy);
                draw(qx, qy, rx, ry);
            } else {
                Koch(ox, oy, px, py, n - 1);
                Koch(px, py, sx, sy, n - 1);
                Koch(sx, sy, qx, qy, n - 1);
                Koch(qx, qy, rx, ry, n - 1);
            }
        }

        function draw(x1, y1, x2, y2) {
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.stroke();
        }
    </script>
</head>

<body onload="init()">
    <canvas id="main_canvas" width="350" height="350" style="background-color:#eeeeee;"></canvas>
</body>

</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0