Skip to content

Instantly share code, notes, and snippets.

@nick-jonas
Last active October 24, 2016 02:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nick-jonas/9815565 to your computer and use it in GitHub Desktop.
Save nick-jonas/9815565 to your computer and use it in GitHub Desktop.
Animating bubbles using Canvas
// called once, to initialize
createBubbles: function(){
var self = this,
el = this.element,
width = $(window).width(),
height = $(window).height(),
canvas = document.createElement('canvas');
el.style.width = canvas.width = width;
el.style.height = canvas.height = height;
el.appendChild(canvas);
var bubbles = [];
var ctx = canvas.getContext('2d');
for(var i = 0; i < this.settings.bubbleCount; i++){
// give random diameter, x, y, opacity, speed, amplitude, and outline or fill
var diam = (Math.random() * (this.settings.maxDiam - this.settings.minDiam)) + this.settings.minDiam,
x = Math.floor(Math.random() * width),
y = height + (diam / 2) + Math.random() * 100,
opacity = Math.random(1),
speed = (Math.random() / 2) + 0.1,
amplitude = (Math.random() * 50) + 45,
isOutline = Math.random() > 0.5;
// store bubble properties in memory
var bubble = {
startX: x,
x: x,
y: y,
radius: diam / 2,
speed: speed,
opacity: self.map_range(opacity, 0, 1, 0, 0.4),
amplitude: amplitude,
isOutline: isOutline
};
bubbles.push(bubble);
}
var count = 0;
// called on each frame
function animate(){
// if not active, place at bottom
if(!$(el).data('isPlaying')){
for(var j = 0; j < bubbles.length; j++){
bubbles[j].y = height + (diam / 2);
}
return;
}
count++;
// clear canvas
ctx.clearRect(0, 0, width, height);
for(var i = 0; i < bubbles.length; i++){
var b = bubbles[i];
// if reached top, send back to bottom
if(b.y <= b.radius * -2){
b.y = window.innerHeight + b.radius;
}
// move upwards, with repetitive oscillation on the x-axis
b.y = b.y - b.speed;
b.x = b.startX + Math.sin(count / b.amplitude) * 50;
ctx.beginPath();
// outline some, fill others
if(b.isOutline){
ctx.strokeStyle = 'rgb(94,202,255)';
ctx.lineWidth = 2;
ctx.arc(b.x, b.y, b.radius, 0, 2 * Math.PI, false);
ctx.stroke();
}else{
ctx.fillStyle = 'rgba(94,202,255, ' + b.opacity + ')';
ctx.arc(b.x, b.y, b.radius, 0, 2 * Math.PI, false);
ctx.fill();
}
}
}
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
(function animloop(){
requestAnimFrame(animloop);
animate();
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment