Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created June 7, 2013 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/5730125 to your computer and use it in GitHub Desktop.
Save tmcw/5730125 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>sphere</title>
<meta http-equiv='content-type' content='text/html; charset=utf-8' />
<meta name='viewport' content='initial-scale=1.0 maximum-scale=1.0'>
<style>
body {
margin:0;
}
canvas {
float:left;
}
</style>
</head>
<body>
<canvas width=600 height=300 id='c'></canvas>
<canvas width=300 height=300 id='c2'></canvas>
<script src='index.js'></script>
</body>
</html>
var points = (function() {
var p = [];
for (var x = -180; x < 180; x += 5) {
for (var y = -90; y < 90; y += 5) {
p.push([x, y]);
}
}
return p;
})();
var c = document.getElementById('c'),
ctx = c.getContext('2d');
var c2 = document.getElementById('c2'),
ctx2 = c2.getContext('2d');
var ew = 600, eh = 300;
ctx2.transform = 'scale(0.5)';
function ex(_) {
return (_ + 180) * (600 / 360);
}
function ey(_) {
return (_ + 90) * (300 / 180);
}
function col(_) {
var r = ((_[0] + 180) * (256 / 360)).toFixed(0);
var g = (255 - (_[1] + 90) * (256 / 180)).toFixed(0);
return 'rgb(' + r + ',' + g + ',' + (255 - g) + ')';
}
var sw = 300, sh = 300;
function multiMap(a, f) {
return a.map(function(_) {
return [f(_), _];
});
}
function spherical2cartesian(ll) {
var rad = Math.PI / 180;
var lat = ll[1] * rad;
var lon = ll[0] * rad;
var cos = Math.cos(lat);
return [cos * Math.cos(lon), Math.sin(lat), cos * Math.sin(lon)];
}
function sx(_) {
return (_ + Math.PI / 2) * (sw / Math.PI);
}
function sy(_) {
return (_ + Math.PI / 2) * (sh / Math.PI);
}
function draw() {
c.width = c.width;
c2.width = c2.width;
points.forEach(function(p) {
ctx.fillStyle = col(p);
ctx.fillRect(
~~ex(p[0]),
~~ey(p[1]), 4, 4);
});
multiMap(points, spherical2cartesian).filter(function(p) {
return p[0][2] > 0;
}).forEach(function(p) {
ctx2.fillStyle = col(p[1]);
ctx2.fillRect(
~~sx(p[0][0]),
~~sy(p[0][1]), 2, 2);
});
}
function modify() {
for (var i = 0; i < points.length; i++) {
points[i][0] += 0.1;
points[i][1] += 0.8;
if (points[i][0] > 180) points[i][0] -= 360;
if (points[i][1] > 90) points[i][1] -= 180;
}
}
function loop() {
modify();
draw();
(window.webkitRequestAnimationFrame || window.setTimeout)(loop, 0);
}
loop();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment