Skip to content

Instantly share code, notes, and snippets.

@jbeuckm
Last active December 19, 2015 14:48
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jbeuckm/5971531 to your computer and use it in GitHub Desktop.
Canvas Particles (2000)
<html>
<head>
<style>
body {
margin: 0
}
#container {
position: absolute;
background-color: #000;
}
</style>
</head>
<body>
<canvas id="container">
</canvas>
<script>
var sprites = [];
var count = 0;
var globe = new Image();
globe.src = 'globe.png';
function addSprite() {
var sprite = {
vx: Math.random(),
vy: Math.random(),
x: Math.random() * 300,
y: Math.random() * 300,
image: globe
};
sprites.push(sprite);
count++;
}
for ( i = 0; i < 2000; i++) {
addSprite();
}
var canvas = document.getElementById('container');
var width = 960;
var height = 500;
var ctx = canvas.getContext('2d');
var s, t, i;
function render() {
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
for ( i = 0, l = count; i < l; i++) {
s = sprites[i];
s.x += s.vx;
s.y += s.vy;
dx = clientX - s.x;
dy = clientY - s.y;
dist = Math.sqrt(dx * dx + dy * dy);
if (dist > 0) {
co = .3 / dist;
s.vx += co * dx;
s.vy += co * dy;
}
// drag
s.vx *= .995;
s.vy *= .995;
ctx.drawImage(s.image, ~~s.x, ~~s.y);
}
}
var clientX = 50, clientY = 50;
document.addEventListener('mousemove', function(e) {
clientX = e.clientX;
clientY = e.clientY;
});
var transformProperty;
function setupBrowser() {
if (window.requestAnimationFrame) {
window.requestAnimFrame = window.requestAnimationFrame;
transformProperty = 'transform';
} else if (window.webkitRequestAnimationFrame) {
window.requestAnimFrame = window.webkitRequestAnimationFrame;
transformProperty = 'webkitTransform';
} else if (window.mozRequestAnimationFrame) {
window.requestAnimFrame = window.mozRequestAnimationFrame;
transformProperty = 'MozTransform';
} else {
window.requestAnimFrame = function(callback) {
window.setTimeout(callback, 1000 / 60);
};
}
}
setupBrowser();
(function animloop() {
window.requestAnimFrame(animloop);
render();
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment