LoginSignup
16

More than 5 years have passed since last update.

「プログラムでシダを描画する」をDartで描画する

Last updated at Posted at 2014-05-23

こちらの記事の

プログラムでシダを描画する - 強火で進め

で、Processingにてシダの描画を行っていたので、同じものをDartで書いてみました。

Chromeで実行した結果を先にお見せしますと、こうなります。

スクリーンショット 2014-05-23 9.39.29.png

美しい。

コードは以下のようになります。

pubspec.yaml
name: shida
dependencies:
    browser: any
shida.html
<!-- Google の HTML Style Guide 的な省略方法 -->
<!DOCTYPE html>
<title>シダ</title>
<canvas id="canvas" width="500px" height="500px"></canvas>
<script type="application/dart" src="shida.dart"></script>
<script src="packages/browser/dart.js"></script>
shida.dart
import 'dart:math';
import 'dart:html';

CanvasRenderingContext2D ctx;
const int width = 500;
const int height = 500;

int N = 20;
num xm = 0;
num ym = 0.5;
num h = 0.6;

Random random = new Random();

num W1x(num x, num y) {
  return 0.836 * x + 0.044 * y;
}

num W1y(num x, num y) {
  return -0.044 * x + 0.836 * y + 0.169;
}

num W2x(num x, num y) {
  return -0.141 * x + 0.302 * y;
}

num W2y(num x, num y) {
  return 0.302 * x + 0.141 * y + 0.127;
}

num W3x(num x, num y) {
  return 0.141 * x - 0.302 * y;
}

num W3y(num x, num y) {
  return 0.302 * x + 0.141 * y + 0.169;
}

num W4x(num x, num y) {
  return 0;
}

num W4y(num x, num y) {
  return 0.175337 * y;
}

void f(int k, num x, num y) {
  if (0 < k) {
    f(k - 1, W1x(x, y), W1y(x, y));
    if (random.nextDouble() < 0.3) f(k - 1, W2x(x, y), W2y(x, y));
    if (random.nextDouble() < 0.3) f(k - 1, W3x(x, y), W3y(x, y));
    if (random.nextDouble() < 0.3) f(k - 1, W4x(x, y), W4y(x, y));
  } else {
    num s = 409;
    point(x * s + width * 0.5, height - y * s);
  }
}

void point(num x, num y) {
  ctx.fillRect(x, y, 1, 1);
}

main() {
  CanvasElement canvas = document.query('#canvas');
  ctx = canvas.getContext('2d');
  ctx.fillStyle = 'rgb(0, 128, 0)';

  f(N, 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
16