Skip to content

Instantly share code, notes, and snippets.

@SS1031
Last active December 28, 2015 18:29
Show Gist options
  • Save SS1031/7543802 to your computer and use it in GitHub Desktop.
Save SS1031/7543802 to your computer and use it in GitHub Desktop.
シェルピンスキーのギャスケット
var SCREEN_SIZE = 500; // キャンバスの幅
var canvas; //= document.getElementById('world');
var context; //= canvas.getContext('2d');
window.onload = function() {
canvas = document.getElementById('world');
canvas.width = canvas.height = SCREEN_SIZE;
var scaleRate = Math.min(window.innerWidth/SCREEN_SIZE, window.innerHeight/SCREEN_SIZE);
canvas.style.width = canvas.style.height = SCREEN_SIZE*scaleRate+'px';
context = canvas.getContext('2d');
context.fillStyle = 'rgb(145, 197, 255)'; // かっこいい色
init();
}
function init() {
var width = SCREEN_SIZE;
var height = Math.sqrt(3)/2 * SCREEN_SIZE;
var count = 7; // リピートの回数
// はじめの三角形の描画
var x0 = width/2;
var y0 = 0;
var x1 = 0;
var y1 = height;
var x2 = width;
var y2 = height;
drawTriangle(x0, y0, x1, y1, x2, y2);
context.fillStyle = "black";
gasket(x0, y0, x1, y1, x2, y2, count);
}
/*
* 三点を入力すると三角形を描画する関数
*/
function drawTriangle(x0, y0, x1, y1, x2, y2) {
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.lineTo(x2, y2);
context.lineTo(x0, y0);
context.fill();
}
function gasket(x0, y0, x1, y1, x2, y2, count) {
if(count > 0) {
// 辺の中心を計算
var x01 = (x0 + x1)/2;
var y01 = (y0 + y1)/2;
var x12 = (x1 + x2)/2;
var y12 = (y1 + y2)/2;
var x02 = (x0 + x2)/2;
var y02 = (y0 + y2)/2;
drawTriangle(x01, y01, x12, y12, x02, y02);
if(count > 1) {
// 再帰的に周りの3つの三角を塗りつぶす
gasket(x0, y0, x01, y01, x02, y02, count - 1);
gasket(x02, y02, x12, y12, x2, y2, count - 1);
gasket(x01, y01, x1, y1, x12, y12, count - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment