Skip to content

Instantly share code, notes, and snippets.

@ManasN
Created September 14, 2015 10:12
Show Gist options
  • Save ManasN/3c9076686d64105054db to your computer and use it in GitHub Desktop.
Save ManasN/3c9076686d64105054db to your computer and use it in GitHub Desktop.
Parallax Squares
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var c = document.createElement("canvas");
document.body.appendChild(c);
function getContext() {
ctx = c.getContext("2d");
c.width = window.innerWidth;
c.height = window.innerHeight;
var cubes = [],
//more spacing less squares
spacing = 40,
xPos = 0,
n = window.innerWidth / spacing,
tSpeedFactor = [.2, .4, .6, .8, 1],
i;
var colors = ['#556270', '#4ECDC4', '#C7F464', '#FF6B6B', '#C44D58'];
for (i = 0; i < n; i++) {
cubes.push({
x: xPos,
y: Math.round(Math.random() * c.height),
width: Math.round(Math.random() * 5) * 10,
tSpeed: tSpeedFactor[Math.floor(Math.random() * tSpeedFactor.length)],
color: colors[Math.floor(Math.random() * colors.length)],
angle: 0,
upDownFactor: (Math.random() >= .5) ? 1 : -1
});
xPos += spacing;
}
function draw() {
var i;
ctx.clearRect(0, 0, c.width, c.height);
for (i = 0; i < n; i++) {
ctx.save();
ctx.translate(cubes[i].x + cubes[i].width / 2, cubes[i].y + cubes[i].width / 2);
ctx.rotate(cubes[i].angle);
ctx.fillStyle = cubes[i].color;
ctx.globalAlpha = .75;
ctx.fillRect(-cubes[i].width / 2, -cubes[i].width / 2, cubes[i].width, cubes[i].width);
ctx.restore();
cubes[i].y = cubes[i].y + cubes[i].tSpeed * cubes[i].upDownFactor;
cubes[i].angle += Math.PI / 360;
if (cubes[i].upDownFactor === -1) {
if (cubes[i].y + cubes[i].width < 0) {
cubes[i].y = c.height;
}
} else if (cubes[i].upDownFactor === 1) {
if (cubes[i].y >= c.height) {
cubes[i].y = -cubes[i].width;
}
}
}
window.requestAnimationFrame(draw);
}
draw();
};
getContext();
window.addEventListener('resize', getContext);
<script src="https://cdn.rawgit.com/Siddharth11/gradStop.js/master/gradstop.js"></script>
canvas {
position: fixed;
/* Force Hardware Acceleration */
transform: translate3d(0, 0, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment