Created
July 24, 2014 03:40
-
-
Save ccarruitero/351bba31b197d9c05383 to your computer and use it in GitHub Desktop.
playing with 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
// canvas animation | |
window.requestAnimationFrame = window.requestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.msRequestAnimationFrame; | |
var circles = []; | |
var canvas = document.getElementById('animation'); | |
var ctx = canvas.getContext('2d'); | |
function initCanvas() { | |
setCanvasDimentions(); | |
animate(); | |
} | |
function setCanvasDimentions() { | |
ctx.canvas.width = window.innerWidth; | |
if (document.body.scrollHeight > 0) { | |
ctx.canvas.height = document.body.scrollHeight; | |
} else { | |
ctx.canvas.height = document.documentElement.scrollHeight; | |
} | |
} | |
function animate() { | |
var canvasAnim = requestAnimationFrame(draw); | |
window.addEventListener('resize', onResize, false); | |
} | |
function onResize() { | |
setCanvasDimentions(); | |
} | |
function createCircle(w, color, x ,y) { | |
this.x = x; | |
this.y = y; | |
this.dx = Math.cos( Math.PI * Math.round( Math.random())); | |
this.dy = Math.cos( Math.PI * Math.round( Math.random())); | |
this.w = w; | |
this.color = color; | |
} | |
function draw() { | |
// clean canvas | |
ctx.clearRect(0,0,canvas.width,canvas.height); | |
ctx.fillStyle = 'rgba(0,0,0,0.4)'; | |
// render circles | |
for (var i=0; i < circles.length; i++) { | |
var circle = circles[i]; | |
ctx.beginPath(); | |
ctx.fillStyle = circle.color; | |
ctx.arc(circle.x,circle.y,circle.w,0,Math.PI*2, false); | |
ctx.arc(circle.x,circle.y,circle.w/3,0,Math.PI*2, true); | |
ctx.fill(); | |
ctx.closePath(); | |
// limit area to bounce | |
if( circle.x<0 || circle.x>canvas.width) circle.dx=-circle.dx; | |
if( circle.y<0 || circle.y>canvas.height) circle.dy=-circle.dy; | |
circle.x+=circle.dx; | |
circle.y+=circle.dy; | |
} | |
requestAnimationFrame(draw); | |
} | |
circles.push(new createCircle(150, 'rgba(62,130,187,0.7)', 0, 250)); | |
circles.push(new createCircle(90, 'rgba(89,173,124,0.7)', 995, 75)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment