18

More than 5 years have passed since last update.

posted at

updated at

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

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

## ソースコード

index.html
<!doctype html>

<html>
<meta charset="utf-8">
<title>Draw leaves of the fern by a program</title>
<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で出力できます。

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
What you can do with signing up
18