Skip to content

Instantly share code, notes, and snippets.

@alash3al
Created November 25, 2015 11:43
Show Gist options
  • Save alash3al/23b4dfceda39b78ced5b to your computer and use it in GitHub Desktop.
Save alash3al/23b4dfceda39b78ced5b to your computer and use it in GitHub Desktop.
just move+falling-balls animations
<!-- www.alash3al.xyz -->
<style>
* {
margin: 0;
padding: 0;
}
body {
background: #000;
overflow: hidden;
}
#ship {
width: 80px;
height: 80px;
position: absolute;
right: 200px;
bottom: 0;
}
</style>
<script>
var H = window.innerHeight
var W = window.innerWidth
var BALLS = []
var COLORS = ["red", "green", "yellowgreen", "blue", "black", "white", "greenyellow", "orange", "maroon"]
function makeBall(id) {
ball = document.createElement("div")
ball.id = "ball-" + id
ball.style.background = COLORS[Math.round(COLORS.length * Math.random())]
ball.style.borderRadius = "50%"
ball.style.display = "inline-block"
ball.style.position = "absolute"
ball.style.margin = "auto"
ball.style.top = (H * Math.random()) + "px"
ball.style.left = (W * Math.random()) + "px"
ball.style.width = "5px"
ball.style.height = "5px"
return ball
}
function drawBalls(count) {
for ( i = 0; i < count; i ++ ) {
id = i + 1
ball = makeBall(id)
BALLS.push(id)
document.body.appendChild(ball)
}
}
function moveBalls() {
for ( var k in BALLS ) {
id = BALLS[k]
ball = document.getElementById("ball-" + id)
ball.style.top = (H * Math.random()) + "px"
ball.style.left = (W * Math.random()) + "px"
ball.style.width = ball.style.height = (8 * Math.random()) + "px"
}
}
function mv(obj, x, y) {
right = parseInt(obj.style.right || 200)
bottom = parseInt(obj.style.bottom || 0)
if ( (x != "undefined") && (obj.offsetLeft >= 0) && (right >= 0) ) {
if ( ((obj.offsetLeft - x) >= 0) && ((right + x) >= 0) ) {
obj.style.right = (right + x) + "px"
}
}
if ( (y != "undefined") && (obj.offsetTop >= 0) && (bottom >= 0) ) {
if ( ((obj.offsetTop - y) >= 0) && ((bottom + y) >= 0) ) {
obj.style.bottom = (bottom + y) + "px"
}
}
}
window.onload = function(){
// draw white balls
drawBalls(100)
// move the generated balls "and change some attrs"
setInterval(moveBalls, 1500)
// handle keyboard buttons
window.onkeydown = function(e){
ship = document.getElementById("ship")
//console.log(e.keyCode)
switch(e.keyCode) {
// right
case 39:
mv(ship, -5)
return false
// left
case 37:
mv(ship, 5)
return false
// top
case 38:
mv(ship, undefined, 5)
return false
// bottom
case 40:
mv(ship, undefined, -5)
return false
}
}
}
</script>
<img id="ship" src="http://icons.iconarchive.com/icons/everaldo/crystal-clear/128/App-launch-spaceship-icon.png">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment