Last active
October 24, 2016 02:55
-
-
Save nick-jonas/9815565 to your computer and use it in GitHub Desktop.
Animating bubbles using Canvas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| createBubbles: function(){ | |
| var self = this, | |
| el = this.element, | |
| width = $(window).width(), | |
| height = $(window).height(), | |
| canvas = document.createElement('canvas'); | |
| if(this.settings.canvasId) $(canvas).attr('id', this.settings.canvasId); | |
| 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++){ | |
| 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; | |
| 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; | |
| function animate(){ | |
| if(!$(el).data('isPlaying')){ | |
| for(var j = 0; j < bubbles.length; j++){ | |
| bubbles[j].y = height + (diam / 2); | |
| } | |
| return; | |
| } | |
| count++; | |
| 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; | |
| } | |
| b.y = b.y - b.speed; | |
| b.x = b.startX + Math.sin(count / b.amplitude) * 50; | |
| ctx.beginPath(); | |
| 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