Skip to content

Instantly share code, notes, and snippets.

@vssranganadhp
Created April 16, 2013 04:59
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 vssranganadhp/5393468 to your computer and use it in GitHub Desktop.
Save vssranganadhp/5393468 to your computer and use it in GitHub Desktop.
A CodePen by Noel Delgado.
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
W = document.body.offsetWidth,
H = document.body.offsetHeight,
COLOURS = [ "#0B9CB6", "#1A7795", "#295376", "#372E53" ],
A = new Node(),
B = new Node();
document.body.appendChild( canvas );
var g = ctx.createLinearGradient(0, 0, W, H),
intervals = 100 / COLOURS.length,
interval = 0;
for (var i = 0; i < COLOURS.length; i += 1) {
g.addColorStop( "." + interval, COLOURS[i] );
interval += intervals;
}
function Node( x, y ) {
this.x = Math.random() * W;
this.y = Math.random() * H;
this.vx = Math.random() * 15;
this.vy = Math.random() * 15;
this.radius = 3;
this.colour = COLOURS[ ~~( Math.random() * COLOURS.length ) ];
}
var setSize = function(){
W = window.innerWidth;
H = window.innerHeight;
canvas.width = W;
canvas.height = H;
};
var fillNode = function( NODE ) {
ctx.fillStyle = g;
ctx.arc( NODE.x, NODE.y, NODE.radius, Math.PI * 2, false);
ctx.fill();
};
var render = function() {
ctx.globalCompositeOperation = 'lighter';
ctx.globalAlpha = 0.1;
fillNode(A);
fillNode(B);
ctx.globalAlpha = 1;
ctx.beginPath();
ctx.lineWidth = 1;
ctx.moveTo( A.x, A.y );
ctx.lineTo( B.x, B.y );
ctx.strokeStyle = g;
ctx.stroke();
ctx.closePath();
};
var update = function() {
A.x += A.vx;
A.y += A.vy;
B.x += B.vx;
B.y += B.vy;
if ( is_colliding(A) || is_colliding(B) ) {
A.colour = COLOURS[ ~~(Math.random() * COLOURS.length)];
B.colour = COLOURS[ ~~(Math.random() * COLOURS.length)];
}
};
var is_colliding = function( NODE ) {
if (NODE.x < 0) {
NODE.x = 0;
NODE.vx *= -1;
return true;
}
if (NODE.x > W) {
NODE.x = W;
NODE.vx *= -1;
return true;
}
if (NODE.y < 0) {
NODE.y = 0;
NODE.vy *= -1;
return true;
}
if (NODE.y > H) {
NODE.y = H;
NODE.vy *= -1;
return true;
}
return false;
};
var draw = function() {
requestAnimFrame(draw);
update();
render();
}
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ) {
window.setTimeout(callback, 1000 / 60);
}
})();
window.addEventListener('load', setSize, false);
window.addEventListener('resize', setSize, false);
draw();
@import "compass"
html, body
width: 100%
height: 100%
background-color: #222
margin: 0
canvas
display: block
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment