Last active
August 29, 2015 14:23
-
-
Save joshblack/a73f384e5a9034fcd446 to your computer and use it in GitHub Desktop.
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
// particle | |
// particle() -> DOM node | |
function particle() { | |
const node = document.createElement('div'); | |
node.style.background = 'black'; | |
node.style.position = 'absolute'; | |
node.style.width = px(50); | |
node.style.height = px(50); | |
node.style.borderRadius = '50%'; | |
return node; | |
} | |
// insert(node, position: vector) -> DOM node | |
function insert(node, position) { | |
const { translate } = transform; | |
node.style.transform = translate(...position.map(px)); | |
return document.body.appendChild(node); | |
} | |
// position(node) -> vector | |
function position(node) { | |
const translate = node.style.transform, | |
p = translate.slice(10, translate.length - 1); | |
return p.split(',').map((s) => parseInt(s.trim(), 10)); | |
} | |
// remove(node) -> Node that was removed | |
function remove(node) { | |
return node.parentNode.removeChild(node); | |
} | |
function shift(node, to) { | |
const { translate } = transform; | |
node.style.transform = translate(...to.map(px)); | |
return node; | |
} | |
function move(node, velocity) { | |
const shifted = shift(node, add(position(node), velocity)); | |
requestAnimationFrame(move.bind(null, shifted, velocity)); | |
} | |
// Usage | |
// Composable methods | |
position(insert(particle(), [50, 50])); | |
remove(insert(particle(), [50, 50])); | |
// Shift example | |
const p = insert(particle(), [0, 0]); | |
shift(p, [100, 100]); | |
// Early move example | |
const p = insert(particle(), [0, 0]); | |
move(p, [5, 5]); | |
// Fun early experiment | |
function move(node, velocity) { | |
const shifted = shift(node, add(position(node), velocity)); | |
requestAnimationFrame( | |
move.bind(null, shifted, [random(), random()])); | |
} | |
function random() { | |
const sign = Math.floor(Math.random() * 2) === 1 ? 1 : -1; | |
return sign * Math.floor(Math.random() * 2); | |
} | |
const p = insert( | |
particle(), | |
[innerWidth / 2 - 25, innerHeight / 2 - 25] | |
); | |
move(p, [random(), random()]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment