tunnel start location
tunnel ellipses from objects with random starts connected to parent
by rob Davis
HTML
<div id="container">
<div>
<canvas id="starfield" />
</div>
<div>
<canvas id="tunnel" />
</div>
</div>
CSS
#container { background-color:yellow;
width:500px;
height:500px;
position:relative;
}
#tunnel {position:absolute; top:0px; left:0px; }
#starfield {position:absolute; top:0px; left:0px; }
JavaScript
drawStarfield('starfield');
var tunnel = createTunnel(200, 200);
drawTunnel('tunnel', tunnel);
function createTunnel(cx, cy) {
var max=40;
var newTunnel = [];
newTunnel.push({"x":cx, "y":cy, "z": 0.2});
for (var i=0;i<max;i++) {
newTunnel.push(new tunnelElement(newTunnel[i]));
newTunnel[newTunnel.length-1].z += (i/max);
}
return newTunnel;
}
function tunnelElement(parent) {
var distance = 10;
this.x = parent.x + getRandomRange(0, distance)-(distance/2);
this.y = parent.y + getRandomRange(0, distance)-(distance/2);
this.z = parent.z;
}
function drawTunnel(elementId, tunnel) {
var canvas = document.getElementById(elementId);
var context = canvas.getContext('2d');
var width=400;
var height=400;
setCanvasSize(canvas, width, height);
var size=0;
var alpha=1.0;
var max= 40;
for (var i=0;i<tunnel.length-1;i++) {
size=tunnel[i].z*10;
alpha = (tunnel[i].z/max)+0.2;
drawTunnelSection(context, tunnel[i].x, tunnel[i].y, alpha, size);
}
}
function drawTunnelSection(context, x, y, z, size) {
var gradient = context.createRadialGradient(1, 1, 0, 1, 1, 1);
gradient.addColorStop(0.95,'rgba(255,255,0,0.0)');
gradient.addColorStop(1.0,'rgba(0,255, 255, '+z+')');
drawEllipse(context, x, y, size, size, gradient);
}
function drawEllipse(context, cx, cy, rx, ry, fill){
context.save();
context.beginPath();
context.translate(cx-rx, cy-ry);
context.scale(rx, ry);
var ellipseFill;
if (typeof(fill)==='function') {
ellipseFill=fill(context);
} else {
ellipseFill=fill;
}
context.arc(1, 1, 1, 0, 2 * Math.PI, false);
context.fillStyle = ellipseFill;
context.fill();
context.closePath();
context.restore();
}
function drawStarfield(elementId) {
var canvas = document.getElementById(elementId);
var context = canvas.getContext('2d');
var width=400;
var height=400;
var...