Skip to content

Instantly share code, notes, and snippets.

@ww24
Created April 29, 2014 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ww24/11391892 to your computer and use it in GitHub Desktop.
Save ww24/11391892 to your computer and use it in GitHub Desktop.
コッホ雪片
/**
* コッホ雪片
*/
// 設定
/*==========================*/
// 初期座標
var a = {x: 10, y: 580};
var b = {x: 1990, y: 580};
// 描画サイズ
var size = {width: 2000, height: 2300};
// 描画色
var style = "rgba(0, 0, 255, 0.5)";
// 再帰回数
var t = 10;
/*==========================*/
var c = {
x: ((a.x - b.x) + Math.sqrt(3) * (a.y - b.y)) / 2 + b.x,
y: - (Math.sqrt(3) * (a.x - b.x) - (a.y - b.y)) / 2 + b.y
};
var Canvas = require("canvas"),
fs = require("fs");
var canvas = new Canvas(size.width, size.height),
ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(255,255,255)";
ctx.fillRect(0, 0, size.width, size.height);
var points = koch(t, [a, b, c, a]);
points.reduce(function (a, b) {
stroke(a, b, style);
return b;
});
// write out
var out_stream = fs.createWriteStream("snowflake.png");
canvas.pngStream().pipe(out_stream);
function koch(t, points) {
if (t-- === 0) return points;
var res = [a];
points.reduce(function (a, b) {
var c = {}, d = {}, e = {};
e.x = b.x - (b.x - a.x) / 3;
e.y = b.y - (b.y - a.y) / 3;
d.x = b.x - (b.x - a.x) / 3 * 2;
d.y = b.y - (b.y - a.y) / 3 * 2;
dx = (a.x - d.x);
dy = (a.y - d.y);
c.x = - (dx + Math.sqrt(3) * dy) / 2 + d.x;
c.y = (Math.sqrt(3) * dx - dy) / 2 + d.y;
res.push(d, c, e, b);
return b;
});
return koch(t, res);
}
function stroke(a, b, style) {
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.strokeStyle = style;
ctx.stroke();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment