Fishes
by Vladimir
HTML
<div class="aqua">
</div>
<textarea></textarea>
CSS
.aqua {
width: 400px;
height: 400px;
background: darkblue;
position: relative;
}
.fish {
width: 30px;
height: 30px;
overflow: hidden;
position: absolute;
border-radius: 50%;
-webkit-transition: all 100ms ease;
-moz-transition: all 100ms ease;
-o-transition: all 100ms ease;
transition: all 100ms ease;
border:1px solid transparent;
}
.fish:hover {
border:1px solid red;
}
.head {
width:100%;
height:100%;
overflow: hidden;
position: relative;
background: url('http://our-travels.sumy.ua/ost/foto/oform/Knopky/Strelka.gif') 50% 50% no-repeat;
-webkit-transition: all 100ms ease;
-moz-transition: all 100ms ease;
-o-transition: all 100ms ease;
transition: all 100ms ease;
}
JavaScript
var fishesCount = 7;
var fishes = [];
var i = 0;
var changeDirFrequnsy = 2;
var limits = {
height: {
top: 60,
bottom: 310
},
width: {
left: 60,
right: 310
}
}
for(var j = 0; j < fishesCount; j++) {
$('.aqua').append("<div class='fish'><div class='head'></div></div>");
fishes.push({
top: limits.height.top + (limits.height.bottom-limits.height.top)*Math.random(),
left: limits.width.left + (limits.width.right-limits.width.left)*Math.random(),
dirX: 2*Math.random() - 1,
dirY: 2*Math.random() - 1,
speed: 5,
$obj: $('.fish').eq(j)
});
}
setInterval(function() {
i++;
for(var k = 0; k < fishesCount; k++) {
var fish = fishes[k];
//* check borders
if(fish.top > limits.height.bottom && fish.dirY > 0) {
fish.dirY -= 0.6;
} else if(fish.top < limits.height.top && fish.dirY < 0) {
fish.dirY += 0.6;
} else if(fish.left > limits.width.right && fish.dirX > 0) {
fish.dirX -= 0.6;
} else if(fish.left < limits.width.left && fish.dirX < 0) {
fish.dirX += 0.6;
}
if(i%changeDirFrequnsy == 0) {
//* borders OK, random change direction
prop = 'dirX';
if(Math.random() > 0.49) {
prop = 'dirY';
}
//* rotate
if(fish[prop] >= 1 || fish[prop] <= -1) { //* to large!
fish[prop] = 0.8 * fish[prop];
} else {
if(Math.random() > 0.49) {
fish[prop] += 0.2;
} else {
fish[prop] -= 0.2;
}
}
}
fish.top += fish.dirY * fish.speed;
fish.left += fish.dirX * fish.speed;
var dir = 90-180*Math.atan2(fish.dirX,fish.dirY)/Math.PI;
fish.$obj.css({
top: fish.top,
left: fish.left
});
...