// From Paul Irish' post: http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ // shim layer with setTimeout fallback window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); // Vars var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'), width = window.innerWidth, height = window.innerHeight, boxes = [], boxesIndex = 0, boxesNum = 1, centerY = height / 2, centerX = width / 2, tracker = 0, hues = [301, 206, 348, 172], color = 'hsla(' + hues[Math.floor(Math.random() * 4)] + ', 100%, 54%, 1)', TWO_PI = 2 * Math.PI; canvas.height = height; canvas.width = width; function Box(i) { boxesIndex++; boxes[boxesIndex] = this; this.x = centerX; this.y = centerY; this.color = color; this.i = i; } Box.prototype.draw = function() { ctx.lineWidth = 2; ctx.strokeStyle = this.color; speed = (tracker * .05); center = speed/2; // Tunnel ctx.save(); ctx.translate(centerX, centerY); ctx.rotate(speed); // Radians ctx.strokeRect(-50 * speed, -50 * speed, 100 * speed, 100 * speed); // x and y = Negative halfs of width and height ctx.restore(); // Change color and reset tracker with box reaches the window edge if(height > width && tracker*4 > height || height < width && tracker*4 > width) { tracker = 0; this.color = 'hsla(' + hues[Math.floor(Math.random() * 4)] + ', 100%, 54%, 1)'; } } // Keep track of time function timeTrack() { tracker++; } function createBox() { for(var i = 0; i < boxesNum; i++) { new Box(i); } } // Init createBox(); draw(); // rAF loop function draw() { requestAnimFrame(draw); ctx.fillStyle = 'rgba(18, 26, 31, .1)'; ctx.fillRect(0, 0, width, height); // Draw function for(var i in boxes) { boxes[i].draw(); } // Time tracker timeTrack(); };