ツナドーナツ・技術メモ帳

色々なものを作る過程で分からなかったことなどを書いていきます

コッホ曲線を描く(未完成)

コッホ曲線を描く(未完成)
失敗だけど面白い形ができるのでとっておく

<!DOCTYPE html>
<html lang="ja">
<head>
  <title>コッホ曲線を描く</title>
  <meta charset="UTF-8">
  <style>
  #canvas {
    background: #666;
  }
  </style>

  <script>
  function drawLoopSquare() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext('2d');
    var width = canvas.width;
    var height = canvas.height;
    var x = 1.0;
    var y = 0.0;
    var plusX = 0.0;
    var plusY = 0.0;
    var size = 2;

    //描画フロー
    function render() {

      /*1番目の時*/
      if(rand() % 2 == 0) {
        plusX = (0.5 * x) + ((Math.sqrt(3) / 6) * y);
        plusY = (Math.sqrt(3) * x) - (0.5 * y);
        x = plusX;
        y = plusY;
        console.log("x:", x, "y:", y);

        ctx.beginPath();
        ctx.fillRect(x * 640, 480 - (y * 480), size, size);

        /*2番目の時*/
      } else if(rand() % 2 != 0) {
        plusX = (0.5 * x) - ((Math.sqrt(3) / 6) * y) + 0.5;
        plusY = (-Math.sqrt(3) / 6 * x) - (0.5 * y) + (Math.sqrt(3) / 6);
        x = plusX;
        y = plusY;
        console.log("x:", x, "y:", y);

        ctx.beginPath();
        ctx.fillRect(x * 640, 480 - (y * 480), size, size);
      }
    }

    for(var i = 0;i < 3000;i++) {
      render();
    }
    /*ランダム関数*/
    function rand(){
      var r;
      r = Math.floor(Math.random() * 10) + 1;
      return r;
      console.log("random:", r);
    }
  }
  drawLoopSquare();
  </script>
</head>
<body>
  <canvas id="canvas" width="640" height="480"></canvas>
  <input type="button" value="start" onclick="drawLoopSquare();"/>
</body>
</html>


ここから実行結果