セルオートマトンの自己増殖(HTML5, JavaScript, CSS3) : デモ
セルオートマトンの自己増殖(HTML5, JavaScript, CSS3) : ZIPファイル(4kb)
フラクタル幾何学、セルオートマトンによる自己増殖。
1.HTML
<!DOCTYPE html> <html lang="jp"> <head> <meta charset="UTF-8" /> <title>Sierpinski Gasket</title> <link href="css/base.css" rel="stylesheet" type="text/css"> <script src="js/base.js"></script> </head> <body> <div id="contents"> <canvas id="canvas" width="300" height="300"> </canvas> </div> </body> </html>
2.CSS
@charset "utf-8"; body { margin:0; padding:0; background-color: #fff; font-family:Helvetica, HiraKakuProN-W3, sans-serif; font-size:25px; color:#fff; } #contents { position: absolute; top: 0; left: 0; width: 300px; height:300px; border: 1px solid #000; overflow:hidden; } #canvas { position: absolute; top: 0; left: 0; width: 300px; height:300px; }
3.JavaScript
base.js
window.addEventListener("load", init, false); function init() { var theCanvas = document.getElementById("canvas"); var centerX = (theCanvas.currentStyle || document.defaultView.getComputedStyle(theCanvas,'')).width; centerX = Number(centerX.replace('px','')); centerX = centerX / 2; var centerY = (theCanvas.currentStyle || document.defaultView.getComputedStyle(theCanvas,'')).height; centerY = Number(centerY.replace('px','')); centerY = centerY / 2; var ctx = theCanvas.getContext("2d"); var w = 7; var h = 7; var sx = 0; var sy = 0; ar = new Array(); var n = 31; var o = 3; centerX = centerX - (n * w / 2); centerY = centerY - (n * h / 2); var amari = 0; for (var i = 1; i <= n*n; i++) { if (i==16) { amari=0; var c = '#000000'; a = 1; } else if (i>=1&&i<33) { amari=0; c = '#ffffff'; a = 0; } else if ((i) % n == 1) { amari=1; var a = (ar[(i + 1 - 1 - n)]) % o; if (a == 0) { c = '#ffffff'; } else if (a == 1) { c = '#000000'; } else if (a == 2) { c = '#cc0000'; } } else if ((i) % n == 0) { amari=0; a = (ar[(i - 1 - 1 - n)]) % o; if (a == 0) { c = '#ffffff'; } else if (a == 1) { c = '#000000'; } else if (a == 2) { c = '#cc0000'; } } else if (i>33) { amari=0; a = (ar[(i - 1 -1 - n)] + ar[(i + 1 - 1 - n)]) % o; //a = (ar[(i - 1 -1 - n)] + ar[(i - 1 - n)] + ar[(i + 1 - 1 - n)]) % o; //a = (ar[(i - 1 -1 - n)] + 2*(ar[(i - 1 - n)])+ar[(i + 1 - 1 - n)]) % o; if (a == 0) { c = '#ffffff'; } else if (a == 1) { c = '#000000'; } else if (a == 2) { c = '#cc0000'; } } else { amari=0; c = '#ffffff'; a = 0; } drawRectangle(ctx, w, h, sx, sy, c, a); sx += w; if (i % n == 0) { sx = 0; sy += h; } } ctx.strokeStyle = '#000000'; ctx.beginPath(); ctx.moveTo(centerX, centerY); ctx.lineTo(centerX, centerY + h*31); ctx.stroke(); ctx.closePath(); function drawRectangle(ctx, w, h, sx, sy, c, a, amari) { ar.push(a); ctx.lineWidth = 1; ctx.strokeStyle = '#000000'; ctx.fillStyle = c; ctx.beginPath(); ctx.moveTo(centerX + sx, centerY + sy); ctx.lineTo(centerX + sx+w, centerY + sy); ctx.lineTo(centerX + sx+w, centerY + sy + h); ctx.lineTo(centerX + sx, centerY + sy + h); ctx.fill(); ctx.stroke(); ctx.closePath(); } }