Created
January 6, 2010 15:16
-
-
Save fedelebron/270326 to your computer and use it in GitHub Desktop.
This file contains 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
<!doctype html> | |
<html> | |
<head> | |
<title>Canvas + JS</title> | |
<style> | |
#canvas { | |
border: 1px solid black; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="canvas" width="800" height="600"></canvas> | |
<script> | |
document.addEventListener('DOMContentLoaded', function() { | |
var canvas = document.getElementById('canvas'); | |
var ctx = canvas.getContext('2d'); | |
ctx.fillStyle = 'black'; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
canvas.addEventListener('mousemove', function(e) { | |
mousex = e.clientX; | |
mousey = e.clientY; | |
}, false); | |
var width = canvas.width, | |
height = canvas.height, | |
x = Math.random() * width, | |
y = Math.random() * height, | |
dx = Math.random(), | |
dy = Math.random(), | |
coeff = 1, | |
i, | |
nBalls = 1, | |
positions = [], | |
deltas = [], | |
hues = Math.random()*360, | |
coeffs = [], | |
oldx, | |
oldy, | |
mousex = width/2, | |
mousey = height/2; | |
function setUpBall(i) { | |
positions[i] = {x:Math.random() * width, y: Math.random() * height}; | |
deltas[i] = {dx: Math.random(), dy: Math.random() }; | |
coeffs[i] = Math.random(); | |
} | |
function moveBall(i) { | |
coeff = Math.pow(-1, Math.floor(Math.random()*10) % 2)*Math.random()*2; | |
oldx = Number(positions[i].x); | |
oldy = Number(positions[i].y); | |
deltas[i].dx += (1-Math.pow((positions[i].x/(width/(3-(mousex/(width/3))+coeff))), 2))/3; | |
deltas[i].dy += (1-Math.pow((positions[i].y/(height/(3-(mousey/(height/3))+coeff))), 2))/3; | |
if(Math.abs(deltas[i].dx) > 15) { deltas[i].dx /= 2; } | |
if(Math.abs(deltas[i].dy) > 15) { deltas[i].dy /= 2; } | |
positions[i].x += deltas[i].dx; | |
positions[i].y += deltas[i].dy; | |
ctx.save(); | |
ctx.fillStyle = ctx.strokeStyle = "hsl("+hues+", 50%, 50%)"; | |
ctx.beginPath(); | |
if(positions[i].x >= 0 && positions[i].y >= 0) { | |
ctx.moveTo(oldx, oldy); | |
ctx.lineTo(positions[i].x, positions[i].y); | |
} | |
ctx.stroke(); | |
ctx.restore(); | |
} | |
for(i = 0; i < nBalls; i++) { | |
setUpBall(i); | |
} | |
function blank() { | |
ctx.fillStyle = 'rgba(0,0,0,0.1)'; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
} | |
function moveBalls() { | |
var i; | |
hues += (10 * Math.random()) % 360; | |
for(i = 0; i < nBalls; i++) { | |
moveBall(i); | |
if(nBalls < 100 && (Math.random() * 100) > 99.2) { | |
setUpBall(nBalls++); | |
} | |
} | |
blank(); | |
} | |
setInterval(moveBalls, 10); | |
}, false); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment