Created
April 29, 2014 06:17
-
-
Save ww24/11391892 to your computer and use it in GitHub Desktop.
コッホ雪片
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* コッホ雪片 | |
*/ | |
// 設定 | |
/*==========================*/ | |
// 初期座標 | |
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