Idea to Code

アイデアをコードへ
独学でプログラミング関係にいろいろ手を出すサイト

hawk

JavaScript

フラクタル図形その22015/12/24

canvas未対応

canvasを用いてフラクタル図形を描画。
赤線を再帰的に繰り返すことで黒線の図形が描画できる。

script.js
var cvr = Math.PI/180;

var canvas = document.getElementById("cv");

var X,Y,R;

function drawLine(r,l){
  ctx.beginPath();
  ctx.moveTo(X, Y);
  ctx.lineTo(X=X + l*Math.cos((R+r) * cvr), Y=Y - l*Math.sin((R+r) * cvr));
  ctx.stroke();

}

function drawFrac1(r, l){
  R += r;
  if (l > 3) {
    drawFrac1(90, l / 2);
    drawFrac1(-90, l / 2);
    drawFrac1(-90, l / 2);
    drawFrac1(90, l / 2);
  }
  else
    drawLine(0,l);
}

function drawFrac2(r, l){
  R += r;
  if (l > 3) {
    drawFrac2(60, l / 2);
    drawFrac2(-120, l / 2);
    drawFrac2(60, l / 2);
  }
  else
    drawLine(0,l);
}

function drawFrac3(r, l){
  R += r;
  if (l > 3) {
    drawFrac3(60, l / 2);
    drawFrac3(-120, l/2);
    drawFrac3(0, l/2);
    drawFrac3(120, l / 2);
    R-=60;
  }
  else
    drawLine(0,l);
}

if (canvas.getContext) {
  var ctx = canvas.getContext("2d");

  ctx.strokeStyle = "#000";
  X = 100;
  Y = 150;
  R = 0;
  drawFrac1(0, 150);

  X = 300;
  Y = 150;
  R = 0;
  drawFrac2(0, 150);

  X = 500;
  Y = 150;
  R = 0;
  drawFrac3(0, 150);

  ctx.strokeStyle = "#f00";
  X = 100;
  Y = 150;
  R = 0;
  drawLine(90, 50);R+=90;
  drawLine(-90, 50);R-=90;
  drawLine(-90, 50);R-=90;
  drawLine(90, 50);

  X = 300;
  Y = 150;
  R = 0;
  drawLine(60, 50);R+=60;
  drawLine(-120, 50);R-=120;
  drawLine(60, 50);

  X = 500;
  Y = 150;
  R = 0;
  drawLine(60, 50);R+=60;
  drawLine(-120, 50);R-=120;
  drawLine(0, 50);
  drawLine(120, 50);
}