18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

「プログラムでシダを描画する」をJavaScript+Canvasで描画する

Last updated at Posted at 2014-05-27

もしかしたら既出かもしれないけど‥‥。

出力結果

シダ

ソースコード

index.html
<!doctype html>

<html>
<head>
<meta charset="utf-8">
<title>Draw leaves of the fern by a program</title>
</head>
<body>
<h1>Draw leaves of the fern by a program</h1>

<canvas id="fern"></canvas>
<input type="text" value="Data URL Here" id="data-url">
<script src="index.js"></script>
</body>
</html>
index.js
(function () {

// Constants
var
// size of canvas#fern
WIDTH  = 500,
HEIGHT = 500;

// Functions
var
lambda = function lambda(expr) {
  return Function(
    'x, y',
    'return ' + expr + ';');
},
W1x = lambda('0.836  * x + 0.044 * y'),
W1y = lambda('-0.044 * x + 0.836 * y + 0.169'),
W2x = lambda('-0.141 * x + 0.302 * y'),
W2y = lambda('0.302  * x + 0.141 * y + 0.127'),
W3x = lambda('0.141  * x - 0.302 * y'),
W3y = lambda('0.302  * x + 0.141 * y + 0.169'),
W4x = lambda('0'),
W4y = lambda('0.175337 * y');

function points(k, x, y, callback) {
  if (0 < k) {
    points(k - 1, W1x(x, y), W1y(x, y), callback);
    if (Math.random() < 0.3)
      points(k - 1, W2x(x, y), W2y(x, y), callback);
    if (Math.random() < 0.3)
      points(k - 1, W3x(x, y), W3y(x, y), callback);
    if (Math.random() < 0.3)
      points(k - 1, W4x(x, y), W4y(x, y), callback);
  } else {
    callback(~~(x * (WIDTH - 10) + WIDTH / 2), ~~(HEIGHT - y * (HEIGHT - 10)));
  }
}

// Main
var
N = 20,
CANVAS_ID = 'fern',
DATA_URL_ID = 'data-url',
COLOR = [0x00, 0x80, 0x00, 0xff];

function initCanvas(canvas) {
  canvas.width  = WIDTH;
  canvas.height = HEIGHT;
  return canvas;
}

var
canvas  = initCanvas(document.getElementById(CANVAS_ID)),
ctx     = canvas.getContext('2d'),
imgData = ctx.createImageData(WIDTH, HEIGHT);

points(N, 0, 0, function callback(x, y) {
  var
  idx = y * WIDTH * 4 + x * 4;
  imgData.data[idx + 0] = COLOR[0];
  imgData.data[idx + 1] = COLOR[1];
  imgData.data[idx + 2] = COLOR[2];
  imgData.data[idx + 3] = COLOR[3];
});

ctx.putImageData(imgData, 0, 0);

document.getElementById(DATA_URL_ID).value = canvas.toDataURL();

})();

Python版のソースコードをJavaScriptに書き直したような感じなので、なぜかlambdaとかあります。何か違うような気がします。

ちなみに

公開しておいたので、暇潰しにでも開いてみてください。

Draw leaves of the fern by a program

乱数使っているので、細いシダになったり太くなったりします。

あとDataURLで出力できます。

18
18
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
18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?