Created
April 22, 2013 12:18
-
-
Save aidiary/ca5b67a9175b804e9560 to your computer and use it in GitHub Desktop.
Barnsley Fernを描画
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 RED = [255, 0, 0, 255]; | |
var GREEN = [0, 255, 0, 255]; | |
var BLUE = [0, 0, 255, 255]; | |
var YELLOW = [255, 255, 0, 255]; | |
$(document).ready(function() { | |
var NUMBER_OF_POINTS = 99999; | |
var canvas = $("#canvas"); | |
var ctx = canvas[0].getContext("2d"); | |
var width = canvas.width(); | |
var height = canvas.height(); | |
var imageData = ctx.createImageData(width, height); | |
var points = generatePoints(NUMBER_OF_POINTS); | |
createImageData(imageData, points); | |
ctx.putImageData(imageData, 0, 0); | |
}); | |
function generatePoints(numPoints) { | |
var points = new Array(); | |
var p = { x:0, y:0, color:GREEN }; | |
points.push(p); | |
for (var i = 0; i < numPoints; i++) { | |
var rand = Math.floor(Math.random() * 100); | |
if (rand <= 3) { | |
p = f1(p); | |
} else if (rand >= 4 && rand <= 76) { | |
p = f2(p); | |
} else if (rand >= 77 && rand <= 90) { | |
p = f3(p); | |
} else if (rand >= 90) { | |
p = f4(p); | |
} | |
points.push(p); | |
} | |
return points; | |
} | |
function createImageData(imageData, points) { | |
var numPoints = points.length; | |
var width = imageData.width; | |
var height = imageData.height; | |
for (var i = 0; i < numPoints; i++) { | |
var p = points[i]; | |
var dx = Math.floor(width/2 + p.x * 50); | |
var dy = height - Math.floor(p.y * 50); | |
var index = (dy * width + dx) * 4; | |
imageData.data[index + 0] = p.color[0]; // red | |
imageData.data[index + 1] = p.color[1]; // green | |
imageData.data[index + 2] = p.color[2]; // blue | |
imageData.data[index + 3] = p.color[3]; // alpha | |
} | |
} | |
function f1(p) { | |
return { x: 0.00, | |
y: 0.16 * p.y, | |
color: GREEN }; | |
} | |
function f2(p) { | |
return { x: 0.85 * p.x + 0.04 * p.y, | |
y: -0.04 * p.x + 0.85 * p.y + 1.60, | |
color: BLUE }; | |
} | |
function f3(p) { | |
return { x: 0.20 * p.x - 0.26 * p.y, | |
y: 0.23 * p.x + 0.22 * p.y + 1.60, | |
color: YELLOW }; | |
} | |
function f4(p) { | |
return { x: -0.15 * p.x + 0.28 * p.y, | |
y: 0.26 * p.x + 0.24 * p.y + 0.44, | |
color: RED }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment