JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"><title>SVG game</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="game"></div>
</body>
</html>
CSS
#game {
width: 380px;
height: 360px;
border: 1px solid #b6b6b6;
margin: 50px auto 0 auto;
position: relative;
font-family: Arial, Helvetica, sans-serif;
/*border-radius: 2px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
-webkit-box-shadow: 0 2px 15px rgba(0,0,0,0.1);
-moz-box-shadow: 0 2px 15px rgba(0,0,0,0.1);*/
}
JavaScript
var $game = $('#game'),
gameWidth = $game.width(),
gameHeight = $game.height(),
paperOffset = $game.offset(),
paper = Raphael('game', 380, 360),
enemyCount = 6,
enemies = new Array(enemyCount),
enemyColors = ["#3f5a5a", "#56532f", "#cac7a3", "#3c5a6d", "#877040", "#574e06", "#fecb00"],
restart = false;
$(document).click(gameOver);
// createEnemies
(function () {
for (var i = 0; i < enemyCount; i++) {
var rectSize = rand(20, 35),
enemy = enemies[i] = paper.rect(rand(0, gameWidth), rand(0, gameHeight),
rectSize * 1.3, rectSize, 3);
enemy.attr({
x: -100,
y: -100,
fill: enemyColors[ rand(0, enemyColors.length) ],
stroke: "none"
});
animateEnemies(enemy);
}
})();
function animateEnemies(enemy) {
var enemyWidth = enemy.attr('width'),
enemyHeight = enemy.attr('height'),
animationDuration = rand(1000, 3000);
enemy.animate({
x: rand(0, gameWidth - enemyWidth),
y: rand(0, gameHeight - enemyHeight)
}, animationDuration, "ease-in-out");
// use setTimout instead of onAnimation callback, since it gave "too much recursion" in Firefox 3.6
this.timeOut = setTimeout(function () {
animateEnemies(enemy);
}, animationDuration);
};
function gameOver() {
enemies.each(function(item) {
item.remove();
clearTimeout(this.timeOut);
});
};
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Array.prototype.each = function (fn, thisp) {
var len = this.length;
for (var i = 0; i < len; i++) {
fn.call(thisp, this[i], i);
}
}