Ray Trace Spheres
by Trevor Dixon
HTML
<script src="http://cloud.github.com/downloads/harthur/color/color-0.4.1.js"></script>
<canvas id="canvas" width="640" height="480"></canvas>
CSS
#canvas { background-color: black; }
JavaScript
/*
Bootstrap/helper stuff
*/
var el = document.getElementById("canvas"),
ctx = el.getContext("2d");
var canvas = ctx.createImageData(el.width, el.height);
canvas.setPixel = function(x, y, r, g, b, a) {
var index = (x + y * canvas.width) * 4;
canvas.data[index+0] = r;
canvas.data[index+1] = g;
canvas.data[index+2] = b;
canvas.data[index+3] = a || 255;
};
canvas.render = function() { ctx.putImageData(canvas, 0, 0); }
/* Vector3 (https://code.google.com/p/mea3d/source/browse/trunk/src/vector.js?r=2) */
function Vector3(e,t,n,r){this.x=e?e:0;this.y=t?t:0;this.z=n?n:0;this.w=r?r:1}Vector3.prototype={toString:function(){return"("+this.x.toFixed(3)+","+this.y.toFixed(3)+","+this.z.toFixed(3)+",w:"+this.w.toFixed(3)+")"},equals:function(e){var t=1e-4;if(Math.abs(this.x-e.x)>t||Math.abs(this.y-e.y)>t||Math.abs(this.z-e.z)>t||Math.abs(this.w-e.w)>t)return false;return true},copy:function(){return new Vector3(this.x,this.y,this.z,this.w)},scale:function(e){return new Vector3(this.x*e,this.y*e,this.z*e)},scale3:function(e,t,n){return new Vector3(this.x*e,this.y*t,this.z*n)},add:function(e){return new Vector3(this.x+e.x,this.y+e.y,this.z+e.z)},subt:function(e){return new Vector3(this.x-e.x,this.y-e.y,this.z-e.z)},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},mag2:function(){return this.x*this.x+this.y*this.y+this.z*this.z},norm:function(){var e=this.mag();return this.scale(1/e)},dot:function(e){return this.x*e.x+this.y*e.y+this.z*e.z},cross:function(e){return new Vector3(this.y*e.z-this.z*e.y,this.z*e.x-this.x*e.z,this.x*e.y-this.y*e.x)}}
function applyLight(color, light) {
var s = light.rgbArray().map(function(c) { return c/255; });
color.setValues('rgb', color.rgbArray().map(function(c, i) { return c * s[i]; }));
}
/*
Ray tracing
*/
var Sphere = function(x, y, z, r) {
this.center = new Vector3(x, y, z);
this.radius = r;
this.color = Color('black');
};
Sphere.prototype.setColor =...