Ullam Spiral - Do post do Zeletron

Carregando...

<!doctype html>
	<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Espiral de Ulam - Zeletron</title>
		
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
		
	<script>
		var canvas, context, hsize, vsize;
	
		function setPixel(imageData, x, y, r, g, b, a) {
			var px = (x + y * imageData.width) * 4;
			imageData.data[px+0] = r;
			imageData.data[px+1] = g;
			imageData.data[px+2] = b;
			imageData.data[px+3] = a;
		}
		
		function eratostenes(n) {
			var array = [], upperLimit = Math.sqrt(n), output = [];
			
			for (var i = 0; i < n; i++) {
				array.push(true);
			}
			
			for (var i = 2; i <= upperLimit; i++) {
				if (array[i]) {
					for (var j = i * i; j < n; j += i) {
						array[j] = false;
					}
				}
			}
			
			return array;
		}
		
		function spiral(maxX, maxY, imageData){
			var x = y = 0, dx = 0, dy = -1;
			var iMax = Math.pow(Math.min(maxX, maxY), 2);
			var maxX2 = maxX / 2, maxY2 = maxY / 2;
			
			var primes = eratostenes(iMax);
			
			for (i = 0; i < iMax; i++){
				if (-maxX2 < x && x <= maxX2 && -maxY2 < y && y <= maxY2){
					if (primes[i+1]){
						setPixel(imageData, maxX2 + x, maxY2 + y, 255, 0, 0, 255);
					} else {
						setPixel(imageData, maxX2 + x, maxY2 + y, 255, 255, 255, 255);
					}
				}
				if ((x == y) || (x < 0 && x == -y) || (x > 0 && x == (1-y))){
					tmp = dx;
					dx = -dy;
					dy = tmp;
				}
				x += dx;
				y += dy;
			}
			
			return imageData;		
		}
		
		$(window).load(function(){
			canvas = $('#canvas_ullam').get(0);
			context = canvas.getContext("2d");
			
			hsize = canvas.width;
			vsize = canvas.height;
			
			var imageData = context.createImageData(hsize, vsize);
			imageData = spiral(hsize, vsize, imageData);
			context.putImageData(imageData, 0, 0);
			
			var img = canvas.toDataURL("image/png");
			$('#imgcanvas').attr('src', img);
			$('#loading').hide(0);
			$('#wrapper').fadeIn(1000);
		}); 
	   
	</script>
	
	<style>
		canvas{
			-webkit-transform: translate3d(0,0,0);
		}
		
		body {
			margin: 0;
			font: 14px/18px "Trebuchet MS",Arial,Helvetica,san-serif;
			text-align: center;
			color: #444;
			background: none;
		}
		
		#loading{
			position: absolute;
			margin-top: -37px;
			margin-left: -105px;
			top: 50%;
			left: 50%;
			width: 220px;
			height: 75px;
			display: block;
			color: #999;
		}
		
		#wrapper{
			position: relative;
			background: transparent;
			width: 1000px;
			margin: 1px auto;
			display: none;
		}
		
	</style>
		
	</head>
	<body>
		<h1>Ullam Spiral</h1>
		<div id="loading">
			<p><strong>Carregando...</strong></p>
			<img src="loading11.gif" alt="" width="220" height="19" />
		</div>
		<div id="wrapper">
			<canvas id="canvas_ullam" width="1000" height="1000" style="display: block; width: 1000px; height: 1000px; border:1px solid #000000; display:none;"></canvas>
			<img src="" alt="" id="imgcanvas">
		</div>
	</body>
	</html>