Related
I'm creating particles for the first time with javascript and I'm not sure if the below code is optimized.
When I create 100 particles on the screen I don't notice that much of an fps drop.
When multiple clicks happen in a row the fps takes major dip.
This is understandable but is there a way to optimize this code more so that multiple clicks will maintain a higher frame rate?
var fps = document.getElementById("fps");
var startTime = Date.now();
var frame = 0;
function tick() {
var time = Date.now();
frame++;
if (time - startTime > 1000) {
fps.innerHTML = (frame / ((time - startTime) / 1000)).toFixed(1);
startTime = time;
frame = 0;
}
window.requestAnimationFrame(tick);
}
tick();
function pop (target) {
let amount = 100;
// Quick check if user clicked the button using a keyboard
const bbox = target.getBoundingClientRect();
const x = bbox.left + bbox.width / 2;
const y = bbox.top + bbox.height / 2;
for (let i = 0; i < 100; i++) {
createParticle(x, y);
}
}
function createParticle (x, y) {
const particle = document.createElement('particle');
document.body.appendChild(particle);
let width = Math.floor(Math.random() * 30 + 8);
let height = width;
let destinationX = (Math.random() - 0.5) * 1000;
let destinationY = (Math.random() - 0.5) * 1000;
let rotation = Math.random() * 2000;
let delay = Math.random() * 200;
particle.style.background = `hsl(${Math.random() * 90 + 270}, 70%, 60%)`;
particle.style.border = '1px solid white';
particle.style.width = `${width}px`;
particle.style.height = `${height}px`;
const animation = particle.animate([
{
transform: `translate(-50%, -50%) translate(${x}px, ${y}px) rotate(0deg)`,
opacity: 1
},
{
transform: `translate(-50%, -50%) translate(${x + destinationX}px, ${y + destinationY}px) rotate(${rotation}deg)`,
opacity: 0
}
], {
duration: Math.random() * 1000 + 5000,
easing: 'cubic-bezier(0, .9, .57, 1)',
delay: delay
});
animation.onfinish = removeParticle;
}
function removeParticle (e) {
e.srcElement.effect.target.remove();
}
document.querySelector(".confetti").addEventListener("click",()=>{pop(document.querySelector(".confetti"));}
);
particle {
position: fixed;
top: 0;
left: 0;
opacity: 0;
pointer-events: none;
background-repeat: no-repeat;
background-size: contain;
}
<div class="wrapper">
<span id="fps">--</span> FPS</div>
<div class="confetti">Square particles</div>
</div>
It would be much quicker if you could add a canvas and instead of adding the elements and styling them, you could just draw things onto the canvas. Then, it can be way faster. If you don't get how to use a canvas with JavaScript, you might want to search it up on something like W3Schools, because they have lots of things you could learn from them.
I hope this helps. Please give me any feedback if you have any. I am new to Stack Overflow, so I want to know how to improve. Thanks and happy coding!
There is an animation of the flight of leaves in pure js. The problem is that it needs to be optimized for maximum performance, because there will be more animations of this kind on the page. Besides optimizing the original SVG image and reducing the number of leaflets, what tips can you give to improve the performance of your code?
var LeafScene = function(el) {
this.viewport = el;
this.world = document.createElement('div');
this.leaves = [];
this.options = {
numLeaves: 6,
wind: {
magnitude: 0,
maxSpeed: 12,
duration: 300,
start: 0,
speed: 10
},
};
this.width = this.viewport.offsetWidth;
this.height = this.viewport.offsetHeight;
this.timer = 0;
this._resetLeaf = function(leaf) {
leaf.x = this.width * 2 - Math.random()*this.width*1.75;
leaf.y = -10;
leaf.z = Math.random()*200;
if (leaf.x > this.width) {
leaf.x = this.width + 10;
leaf.y = Math.random()*this.height/2;
}
if (this.timer == 0) {
leaf.y = Math.random()*this.height;
}
leaf.rotation.speed = Math.random()*10;
var randomAxis = Math.random();
if (randomAxis > 0.5) {
leaf.rotation.axis = 'X';
} else if (randomAxis > 0.25) {
leaf.rotation.axis = 'Y';
leaf.rotation.x = Math.random()*180 + 90;
} else {
leaf.rotation.axis = 'Z';
leaf.rotation.x = Math.random()*360 - 180;
leaf.rotation.speed = Math.random()*3;
}
leaf.xSpeedVariation = Math.random() * 0.8 - 0.4;
leaf.ySpeed = Math.random() + 1.5;
return leaf;
}
this._updateLeaf = function(leaf) {
var leafWindSpeed = this.options.wind.speed(this.timer - this.options.wind.start, leaf.y);
var xSpeed = leafWindSpeed + leaf.xSpeedVariation;
leaf.x -= xSpeed;
leaf.y += leaf.ySpeed;
leaf.rotation.value += leaf.rotation.speed;
var t = 'translateX( ' + leaf.x + 'px ) translateY( ' + leaf.y + 'px ) translateZ( ' + leaf.z + 'px ) rotate' + leaf.rotation.axis + '( ' + leaf.rotation.value + 'deg )';
if (leaf.rotation.axis !== 'X') {
t += ' rotateX(' + leaf.rotation.x + 'deg)';
}
leaf.el.style.webkitTransform = t;
leaf.el.style.MozTransform = t;
leaf.el.style.oTransform = t;
leaf.el.style.transform = t;
if (leaf.x < -10 || leaf.y > this.height + 10) {
this._resetLeaf(leaf);
}
}
this._updateWind = function() {
if (this.timer === 0 || this.timer > (this.options.wind.start + this.options.wind.duration)) {
this.options.wind.magnitude = Math.random() * this.options.wind.maxSpeed;
this.options.wind.duration = this.options.wind.magnitude * 50 + (Math.random() * 20 - 10);
this.options.wind.start = this.timer;
var screenHeight = this.height;
this.options.wind.speed = function(t, y) {
var a = this.magnitude/2 * (screenHeight - 2*y/3)/screenHeight;
return a * Math.sin(2*Math.PI/this.duration * t + (3 * Math.PI/2)) + a;
}
}
}
}
LeafScene.prototype.init = function() {
for (var i = 0; i < this.options.numLeaves; i++) {
var leaf = {
el: document.createElement('div'),
x: 0,
y: 0,
z: 0,
rotation: {
axis: 'X',
value: 0,
speed: 0,
x: 0
},
xSpeedVariation: 0,
ySpeed: 0,
path: {
type: 1,
start: 0,
},
image: 1
};
this._resetLeaf(leaf);
this.leaves.push(leaf);
this.world.appendChild(leaf.el);
}
this.world.className = 'leaf-scene';
this.viewport.appendChild(this.world);
this.world.style.webkitPerspective = "400px";
this.world.style.MozPerspective = "400px";
this.world.style.oPerspective = "400px";
this.world.style.perspective = "400px";
var self = this;
window.onresize = function(event) {
self.width = self.viewport.offsetWidth;
self.height = self.viewport.offsetHeight;
};
}
LeafScene.prototype.render = function() {
this._updateWind();
for (var i = 0; i < this.leaves.length; i++) {
this._updateLeaf(this.leaves[i]);
}
this.timer++;
requestAnimationFrame(this.render.bind(this));
}
var leafContainer = document.querySelector('.falling-leaves'),
leaves = new LeafScene(leafContainer);
leaves.init();
leaves.render();
body, html {
height: 100%;
}
.falling-leaves {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 100%;
max-width: 880px;
max-height: 880px;
transform: translate(-50%, 0);
border: 20px solid #fff;
border-radius: 50px;
background-size: cover;
overflow: hidden;
}
.leaf-scene {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 100%;
transform-style: preserve-3d;
}
.leaf-scene div {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background: url(https://www.flaticon.com/svg/static/icons/svg/892/892881.svg) no-repeat;
background-size: 100%;
transform-style: preserve-3d;
-webkit-backface-visibility: visible;
backface-visibility: visible;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<div class="falling-leaves"></div>
Unless you're using HTML Canvas, vanilla JS solutions are pretty heavy compared to CSS/JS hybrid because of the browser call stack.
It looks like this:
JS > Style > Layout > Paint > Composite
By minimizing the amount of calculations the browser has to do in JS and grouping reads/writes to the DOM you'll see a significant performance increase. The workload can be recorded with Chrome Dev tools under 'Performance' tab. And you'll be able to see every step the browser is taking to display the content. The less steps, the better performance .. simple as that.
You're writing to the DOM every single transform which is heavy even with 3d acceleration.
I usually make use of CSS variables and transitions for dynamic animation that I update in steps.
What you did is great otherwise. Try rendering on a HTML Canvas and your performance problems will vanish. Here's a start:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
But if you want or cant do canvas adapt to utilize CSS to not drop further than the Paint browser call for majority of frames.
https://codepen.io/jesserosenfield/pen/LYNGRXV
var path = anime.path('#prog-svg path'),
pathEl = document.querySelectorAll('#prog-svg path')[0],
mylength = pathEl.getTotalLength(),
mypt1 = pathEl.getPointAtLength(mylength * .10),
mypt2 = pathEl.getPointAtLength(mylength * .25);
var motionPath = anime({
targets: '.prog-circ',
translateX: path('x'),
translateY: path('y'),
rotate: path('angle'),
easing: 'easeInOutCirc',
duration: 5000,
direction: 'alternate',
autoplay: false,
elasticity: 200,
loop: false,
update: function(anim){
console.log(path('x'));
}
});
motionPath.seek(1210);
motionPath.play();
This code does what I want it to do in the broad scheme of things, but I have a more specific use case.
I'm using this SVG as a progress bar on a form:
When the user completes step #1 of the form, I want the circle to animate from point A to point B. When the user completes step #2 of the form, I want the circle to animate from point B to point C... and so on.
While motionpath.seek() gets me to the correct point along the path, it sets the circle there with no animation– is there an equivalent function to seek() that will get ANIMATE the circle rather than just set it?
Furthermore I attempted to use getTotalLength() and getPointAtLength() to try and animate like so:
var motionPath = anime({
targets: '.prog-circ',
translateX: [mypt1.x, mypt2.x],
translateY: [mypt1.y, mypt2.y],
but that did not animate the circle along the path.
Any help much appreciated. Thanks!
With one long path I think it's hard to support moving between points since you need to track current progress and convert it to actual length depending on easing function.
I'd split your <path/> into 3 pieces, generate timeline for animation between those 3 pieces and then easily manipulate moving circle back and forth.
Here's an example of how it can be done:
const svg = document.getElementById('prog-svg');
const pathEl = document.querySelector('#prog-svg path');
const totalLength = pathEl.getTotalLength();
const points = [['A', 10], ['B', 25], ['C', 75], ['D', 90]];
function splitPath() {
const interval = 3;
const toLen = percentage => percentage * totalLength / 100;
const paths = [];
for (let i = 0; i < points.length; i++) {
const from = toLen(points[i][1]);
for (let j = i + 1; j < points.length; j++) {
const to = toLen(points[j][1]);
const segments = [];
for (let k = from; k <= to; k += interval) {
const { x, y } = pathEl.getPointAtLength(k);
segments.push([x, y]);
}
paths.push({
segments, path: `${i}-${j}`
});
}
}
paths.forEach(subPath => {
const subPathEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
subPathEl.setAttribute('class', `st0 st0--hidden`);
subPathEl.setAttribute('d', `M ${subPath.segments.map(([x, y]) => `${x},${y}`).join(' ')}`);
svg.appendChild(subPathEl);
subPath.el = subPathEl;
});
return paths;
}
const subPaths = splitPath();
function addPoint(name, progress) {
const point = pathEl.getPointAtLength(totalLength * progress / 100);
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('fill', '#fff');
text.setAttribute('font-size', '1.6em');
text.textContent = name;
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('r', '30');
circle.setAttribute('fill', '#000');
const g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
g.setAttribute('transform', `translate(${point.x},${point.y})`);
g.appendChild(circle);
g.appendChild(text);
svg.appendChild(g);
// center text
const textBB = text.getBBox();
const centerX = textBB.width / 2;
const centerY = textBB.height / 4;
text.setAttribute('transform', `translate(${-centerX},${centerY})`);
return circle;
}
points.forEach(([name, progress]) => addPoint(name, progress));
const progressCircle = document.querySelector('.prog-circ');
progressCircle.style.display = 'block';
const animations = subPaths.map(subPath => {
const animePath = anime.path(subPath.el);
return anime({
targets: progressCircle,
easing: 'easeInOutCirc',
autoplay: false,
duration: 1000,
translateX: animePath('x'),
translateY: animePath('y'),
rotate: animePath('angle'),
});
});
// move circle to the first point
animations[0].reset();
let currentStep = 0;
function moveTo(step) {
if (step < 0 || step > animations.length) return;
const delta = step - currentStep;
const path = delta > 0 ? `${currentStep}-${step}` : `${step}-${currentStep}`;
const animationIndex = subPaths.findIndex(subPath => subPath.path === path);
const animationToPlay = animations[animationIndex];
if (delta < 0 && !animationToPlay.reversed) {
animationToPlay.reverse();
}
if (delta > 0 && animationToPlay.reversed) {
animationToPlay.reverse();
}
animationToPlay.reset();
animationToPlay.play();
currentStep = step;
pagination.selectedIndex = step;
}
const btnPrev = document.getElementById('btn-prev');
const btnNext = document.getElementById('btn-next');
const pagination = document.getElementById('pagination');
btnPrev.addEventListener('click', () => moveTo(currentStep - 1));
btnNext.addEventListener('click', () => moveTo(currentStep + 1));
pagination.addEventListener('change', (e) => moveTo(+e.target.value));
body {
margin: 0;
}
.st0 {
fill: none;
stroke: #000000;
stroke-width: 5;
stroke-linecap: round;
stroke-miterlimit: 160;
stroke-dasharray: 28;
}
.st0--hidden {
stroke: none;
}
.prog-circ {
display: none;
position: absolute;
border-radius: 100%;
height: 30px;
width: 30px;
top: -15px;
left: -15px;
background: #ccc;
opacity: .7;
}
.form-actions {
margin-top: 2em;
display: flex;
justify-content: center;
}
#pagination,
.form-actions button + button {
margin-left: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js"></script>
<svg id="prog-svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1919.1 155.4">
<g>
<path class="st0" d="M4,84.1c0,0,58.8-57.1,235.1,17.9s348.1,18.9,470.2-44.6C800.6,9.7,869.6-2,953.5,6.6c0,0,19,4.1,38.6,14.4
c20.7,10.9,40.7,40.6,40.7,65.6c0,40.2-29.5,64.8-69.7,64.8s-70.1-29.2-70.1-69.4c0-32.3,31.2-59.6,61.8-61.8
c67.2-4.7,103.5-46.8,375.6,70.1c164.9,70.8,220.1-1.1,371.1-11.7c120.5-8.4,213.7,28.6,213.7,28.6"/>
</g>
</svg>
<div class="prog-circ"></div>
<div class="form-actions">
<button id="btn-prev">Prev</button>
<button id="btn-next">Next</button>
<select id="pagination">
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
<option value="3">D</option>
</select>
</div>
I have been trying to use an Animated Background, using Javascript I found on this link : https://codepen.io/nashvail/pen/wpGgXO
It's working fine. But the problem is that once implemented, it's all over the screen.
I want the animations to be in some particular DIV element of my web page.
Help me Out.
// Some random colors
const colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
const numBalls = 50;
const balls = [];
for (let i = 0; i < numBalls; i++) {
let ball = document.createElement("div");
ball.classList.add("ball");
ball.style.background = colors[Math.floor(Math.random() * colors.length)];
ball.style.left = `${Math.floor(Math.random() * 100)}vw`;
ball.style.top = `${Math.floor(Math.random() * 100)}vh`;
ball.style.transform = `scale(${Math.random()})`;
ball.style.width = `${Math.random()}em`;
ball.style.height = ball.style.width;
balls.push(ball);
document.body.append(ball);
}
// Keyframes
balls.forEach((el, i, ra) => {
let to = {
x: Math.random() * (i % 2 === 0 ? -11 : 11),
y: Math.random() * 12
};
let anim = el.animate(
[
{ transform: "translate(0, 0)" },
{ transform: `translate(${to.x}rem, ${to.y}rem)` }
],
{
duration: (Math.random() + 1) * 2000, // random duration
direction: "alternate",
fill: "both",
iterations: Infinity,
easing: "ease-in-out"
}
);
});
.ball {
position: absolute;
border-radius: 100%;
opacity: 0.7;
}
<div class="ball">
</div>
Like this?
// Some random colors
const colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
const numBalls = 50;
const balls = [];
for (let i = 0; i < numBalls; i++) {
let ball = document.createElement("div");
ball.classList.add("ball");
ball.style.background = colors[Math.floor(Math.random() * colors.length)];
ball.style.left = `${Math.floor(Math.random() * 100)}%`;
ball.style.top = `${Math.floor(Math.random() * 100)}%`;
ball.style.transform = `scale(${Math.random()})`;
ball.style.width = `${Math.random()}em`;
ball.style.height = ball.style.width;
balls.push(ball);
document.getElementById("box").append(ball);
}
// Keyframes
balls.forEach((el, i, ra) => {
let to = {
x: Math.random() * (i % 2 === 0 ? -11 : 11),
y: Math.random() * 12
};
let anim = el.animate(
[
{ transform: "translate(0, 0)" },
{ transform: `translate(${to.x}rem, ${to.y}rem)` }
],
{
duration: (Math.random() + 1) * 2000, // random duration
direction: "alternate",
fill: "both",
iterations: Infinity,
easing: "ease-in-out"
}
);
});
.ball {
position: absolute;
border-radius: 100%;
opacity: 0.7;
}
#box{
width: 300px;
height: 300px;
border: 1px solid red;
position: relative;
overflow: hidden;
}
<div id="box"></div>
The issue is, you are appending balls to the body. That's why they are appearing all over the screen. You have to make a container with some width and height and append the created balls to that container only:
// Some random colors
const colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
const numBalls = 50;
const balls = [];
for (let i = 0; i < numBalls; i++) {
let ball = document.createElement("div");
ball.classList.add("ball");
ball.style.background = colors[Math.floor(Math.random() * colors.length)];
ball.style.left = `${Math.floor(Math.random() * 100)}vw`;
ball.style.top = `${Math.floor(Math.random() * 100)}vh`;
ball.style.transform = `scale(${Math.random()})`;
ball.style.width = `${Math.random()}em`;
ball.style.height = ball.style.width;
balls.push(ball);
document.querySelector('.ballContainer').append(ball);
}
// Keyframes
balls.forEach((el, i, ra) => {
let to = {
x: Math.random() * (i % 2 === 0 ? -11 : 11),
y: Math.random() * 12
};
let anim = el.animate(
[
{ transform: "translate(0, 0)" },
{ transform: `translate(${to.x}rem, ${to.y}rem)` }
],
{
duration: (Math.random() + 1) * 2000, // random duration
direction: "alternate",
fill: "both",
iterations: Infinity,
easing: "ease-in-out"
}
);
});
.ball {
position: absolute;
border-radius: 100%;
opacity: 0.7;
}
.ballContainer{
width: 350px;
height: 175px;
border: 1px solid gray;
position: relative;
overflow: hidden;
background-color: lightgray;
}
<div class="ballContainer">
</div>
The balls run a random path. That means some of balls will go out of bounds (your div).
You can add CSS to hide the scroll bars.
html * {
overflow: hidden;
}
Little premise: I didn't want to make this question, because I thought it was a too personal and generic problem; but after 2 days without any improvement, I couldn't resist anymore.
So basically, my project is an aquarium with multiple fishes inside.
It all works fine, the only problem is that, in short words: the first fish image remains inside the div(it even stops too soon), the second one arrives a bit farther, the third even farther, and so on.
The opposite thing happens with the top margin: going forward, the last fish is always farther from the margin, and I can't find out the reason.
My scope is to keep all the fishes inside the "acquario" div (which has the black borders).
P.S. With sx and dx margins, they have no problem.
var BORDER_LEFT_RIGHT = 7;
var BORDER_TOP_DOWN = 28;
var fishes = new Array();
var nextId = 0;
var heightMax;
var widthMax;
var n; //initial direction, see createFish()
init();
/* light blue fish (dory, to clarify)*/
createFish("https://s18.postimg.org/n8sqmtjkp/pesce1_sx.png", "https://s30.postimg.org/6w8xyqwep/pesce1_dx.png");
/* white and yellow fish */
createFish("https://s28.postimg.org/6aalv0pst/pesce2_sx.png", "https://s29.postimg.org/dxbi0vypz/pesce2_dx.png");
/* dark blue fish */
createFish("https://s24.postimg.org/sbgt8zn6t/pesce3_sx.png", "https://s29.postimg.org/v65opob7r/pesce3_dx.png");
/* white-blue-yellow fish */
createFish("https://s30.postimg.org/62lb9bfwx/pesce4_sx.png", "https://s28.postimg.org/kt5m4ea65/pesce4_dx.png");
/* orange fish */
createFish("https://s18.postimg.org/q5sq0saex/pesce5_sx.png", "https://s18.postimg.org/uqnwe2vex/pesce5_dx.png");
showFishes();
function init() {
heightMax = document.getElementById("acquario").clientHeight - BORDER_TOP_DOWN;
widthMax = document.getElementById("acquario").clientWidth - BORDER_LEFT_RIGHT;
n = 1;
}
function createFish(src1, src2) {
imgFishSX = new Image();
imgFishDX = new Image();
imgFishSX.src = src1;
imgFishDX.src = src2;
n *= -1;
var fish = {
id: nextId,
/* default x position: random number between 1 and widthMax */
x: Math.floor((Math.random() * widthMax - imgFishSX.width) + 1),
/* default y position: random number between 1 and heightMax */
y: Math.floor((Math.random() * heightMax - imgFishSX.height) + 1),
xIncrease: n * getIncrease(),
yIncrease: n * getIncrease(),
imageSX: imgFishSX,
imageDX: imgFishDX
};
addFishToArray((fish));
nextId++;
}
function addFishToArray(fish) {
fishes.push(fish);
}
function showFishes() {
var node = document.getElementById("acquario");
var stringToInner = "";
var src;
/* first, we make the string with all the img filled in */
for (var i = 0; i < fishes.length; i++) {
/* we have to check if the default increase direction was <-- or --> */
fishes[i].xIncrease > 0 ? src = fishes[i].imageSX.src : src = fishes[i].imageDX.src;
/* z-index --> overlap priority */
stringToInner += "<img src =\"" + src +
"\" id=\"" + fishes[i].id + "\" style= \"margin-left: " +
fishes[i].x + "px;margin-top: " + fishes[i].y + "px;z-index: " +
fishes[i].id + ";position: absolute;\">";
stringToInner += "<br>";
}
/* then, we insert it */
node.innerHTML = stringToInner;
/* let's raise hell! */
moveFishes();
}
function getIncrease() {
return Math.floor((Math.random() * 5) + 1);
}
function moveFishes() {
/* scroll the array: we need to check each fish one by one */
for (var i = 0; i < fishes.length; i++) {
moveFish(fishes[i]);
}
/* infinite loop */
setTimeout(function() {
moveFishes()
}, 50);
}
function moveFish(fish) {
/* with this node, I'll apply changes to my html document */
node = document.getElementById(fish.id);
/* we are inside, just move */
if (fish.x > 0 && fish.x < widthMax - node.width && fish.y > 0 && fish.y < heightMax - node.height) {
node.style.marginLeft = fish.x + "px";
node.style.marginTop = fish.y + "px";
fish.x += fish.xIncrease;
fish.y += fish.yIncrease;
/* too --> , we need to get <-- */
} else if (fish.x >= widthMax - node.width) {
node.src = fish.imageDX.src;
fish.xIncrease = -getIncrease();
fish.x += fish.xIncrease;
/* too <-- , we need to get --> */
} else if (fish.x <= 0) {
node.src = fish.imageSX.src;
fish.xIncrease = 5;
fish.x += getIncrease();
/* too up, we need to get down */
} else if (fish.y >= heightMax - node.height) {
fish.yIncrease = -getIncrease();
fish.y += fish.yIncrease;
/* too down, we need to get up */
} else if (fish.y <= 0) {
fish.yIncrease = getIncrease();
fish.y += fish.yIncrease;
}
}
* {
box-sizing: border-box;
}
.row::after {
content: "";
clear: both;
display: block;
}
html {
background: url("https://s24.postimg.org/rakxoa7sl/sfondo.jpg") no-repeat center center fixed;
-webkibact-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
html,
body {
height: 100%;
margin: 0;
}
#main {
margin: 0;
height: 100%;
}
#acquario {
border-bottom: 28px solid black;
border-top: 28px solid black;
border-right: 7px solid black;
border-left: 7px solid black;
height: 100%;
}
<body>
<div id="main">
<div id="acquario">
</div>
</div>
</body>
do you want the fishes to bound off the walls or to hide under the wall? and why do you use margin-left and margin-top instead of top and left properties? it makes the aquarium scrolling. Is it ok now?
var BORDER_LEFT_RIGHT = 7;
var BORDER_TOP_DOWN = 28;
var fishes = new Array();
var nextId = 0;
var heightMax;
var widthMax;
var n; //initial direction, see createFish()
init();
/* light blue fish (dory, to clarify)*/
createFish("https://s18.postimg.org/n8sqmtjkp/pesce1_sx.png", "https://s30.postimg.org/6w8xyqwep/pesce1_dx.png");
/* white and yellow fish */
createFish("https://s28.postimg.org/6aalv0pst/pesce2_sx.png", "https://s29.postimg.org/dxbi0vypz/pesce2_dx.png");
/* dark blue fish */
createFish("https://s24.postimg.org/sbgt8zn6t/pesce3_sx.png", "https://s29.postimg.org/v65opob7r/pesce3_dx.png");
/* white-blue-yellow fish */
createFish("https://s30.postimg.org/62lb9bfwx/pesce4_sx.png", "https://s28.postimg.org/kt5m4ea65/pesce4_dx.png");
/* orange fish */
createFish("https://s18.postimg.org/q5sq0saex/pesce5_sx.png", "https://s18.postimg.org/uqnwe2vex/pesce5_dx.png");
showFishes();
function init() {
heightMax = document.getElementById("acquario").clientHeight + BORDER_TOP_DOWN;
widthMax = document.getElementById("acquario").clientWidth + BORDER_LEFT_RIGHT;
n = 1;
}
function createFish(src1, src2) {
imgFishSX = new Image();
imgFishDX = new Image();
imgFishSX.src = src1;
imgFishDX.src = src2;
n *= -1;
var fish = {
id: nextId,
/* default x position: random number between 1 and widthMax */
x: Math.floor((Math.random() * (widthMax - BORDER_LEFT_RIGHT - imgFishSX.width)) + BORDER_LEFT_RIGHT),
/* default y position: random number between 1 and heightMax */
y: Math.floor((Math.random() * (heightMax - BORDER_TOP_DOWN - imgFishSX.height)) + BORDER_TOP_DOWN),
xIncrease: n * getIncrease(),
yIncrease: n * getIncrease(),
imageSX: imgFishSX,
imageDX: imgFishDX
};
addFishToArray((fish));
nextId++;
}
function addFishToArray(fish) {
fishes.push(fish);
}
function showFishes() {
var node = document.getElementById("acquario");
var stringToInner = "";
var src;
/* first, we make the string with all the img filled in */
for (var i = 0; i < fishes.length; i++) {
/* we have to check if the default increase direction was <-- or --> */
fishes[i].xIncrease > 0 ? src = fishes[i].imageSX.src : src = fishes[i].imageDX.src;
/* z-index --> overlap priority */
stringToInner += "<img src =\"" + src +
"\" id=\"" + fishes[i].id + "\" style= \"left: " +
fishes[i].x + "px;top: " + fishes[i].y + "px;z-index: " +
fishes[i].id + ";position: absolute;\">";
stringToInner += "<br>";
}
/* then, we insert it */
node.innerHTML = stringToInner;
/* let's raise hell! */
moveFishes();
}
function getIncrease() {
return Math.floor((Math.random() * 5) + 1);
}
function moveFishes() {
/* scroll the array: we need to check each fish one by one */
for (var i = 0; i < fishes.length; i++) {
moveFish(fishes[i]);
}
/* infinite loop */
setTimeout(function() {
moveFishes()
}, 50);
}
function moveFish(fish) {
/* with this node, I'll apply changes to my html document */
node = document.getElementById(fish.id);
/* we are inside, just move */
if (fish.x > BORDER_LEFT_RIGHT && fish.x < widthMax - node.width && fish.y > BORDER_TOP_DOWN && fish.y < heightMax - node.height) {
node.style.left = fish.x + "px";
node.style.top = fish.y + "px";
fish.x += fish.xIncrease;
fish.y += fish.yIncrease;
/* too --> , we need to get <-- */
} else if (fish.x >= widthMax - node.width) {
node.src = fish.imageDX.src;
fish.xIncrease = -getIncrease();
fish.x += fish.xIncrease;
/* too <-- , we need to get --> */
} else if (fish.x <= BORDER_LEFT_RIGHT) {
node.src = fish.imageSX.src;
fish.xIncrease = 5;
fish.x += getIncrease();
/* too up, we need to get down */
} else if (fish.y >= heightMax - node.height) {
fish.yIncrease = -getIncrease();
fish.y += fish.yIncrease;
/* too down, we need to get up */
} else if (fish.y <= BORDER_TOP_DOWN) {
fish.yIncrease = getIncrease();
fish.y += fish.yIncrease;
}
}
* {
box-sizing: border-box;
}
.row::after {
content: "";
clear: both;
display: block;
}
html {
background: url("https://s24.postimg.org/rakxoa7sl/sfondo.jpg") no-repeat center center fixed;
-webkibact-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
html,
body {
height: 100%;
margin: 0;
}
#main {
margin: 0;
height: 100%;
}
#acquario {
border-bottom: 28px solid black;
border-top: 28px solid black;
border-right: 7px solid black;
border-left: 7px solid black;
height: 100%;
}
<body>
<div id="main">
<div id="acquario">
</div>
</div>
</body>
I know Pawel has fixed your issue, but I did state I would provide a canvas version so here it is
jsFiddle : https://jsfiddle.net/CanvasCode/zh0b7zrj/1/
HTML :
<canvas id="myCanvas"></canvas>
CSS :
html,
body {
width: 100%;
height: 100%;
margin: 0px;
overflow: hidden;
}
Javascript :
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
var backgroundImage = new Image();
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete
// Fish
function FishObject(xSet, ySet, xSpeed, ySpeed, spriteUrlRight, spriteUrlLeft) {
this.XPos = xSet;
this.YPos = ySet;
this.XDefaultSpeed = xSpeed;
this.YDefaultSpeed = ySpeed;
this.xSpeed = this.XDefaultSpeed;
this.ySpeed = this.YDefaultSpeed;
this.RightSprite = new Image();
this.RightSprite.src = spriteUrlRight;
this.LeftSprite = new Image();
this.LeftSprite.src = spriteUrlLeft;
}
FishObject.prototype.Draw = function(ctx) {
if (this.xSpeed > 0) {
ctx.drawImage(this.RightSprite, this.XPos, this.YPos);
} else {
ctx.drawImage(this.LeftSprite, this.XPos, this.YPos);
}
}
FishObject.prototype.Update = function(ctx) {
this.XPos += this.xSpeed;
this.YPos += this.ySpeed;
if (this.XPos <= 0) {
this.xSpeed = this.XDefaultSpeed;
} else if ((this.XPos + this.RightSprite.width) >= canvas.width) {
this.xSpeed = -this.XDefaultSpeed;
}
if (this.YPos <= 0) {
this.ySpeed = this.YDefaultSpeed;
} else if ((this.YPos + this.RightSprite.height) >= canvas.height) {
this.ySpeed = -this.YDefaultSpeed;
}
}
backgroundImage.src = 'https://s24.postimg.org/rakxoa7sl/sfondo.jpg';
var Fishs = [];
Fishs.push(new FishObject(0, 0, 1, 1, "https://s18.postimg.org/n8sqmtjkp/pesce1_sx.png",
"https://s30.postimg.org/6w8xyqwep/pesce1_dx.png"));
Fishs.push(new FishObject(0, 0, 2, 1.2, "https://s28.postimg.org/6aalv0pst/pesce2_sx.png",
"https://s29.postimg.org/dxbi0vypz/pesce2_dx.png"));
Fishs.push(new FishObject(0, 0, 1.7, 2.8, "https://s24.postimg.org/sbgt8zn6t/pesce3_sx.png",
"https://s29.postimg.org/v65opob7r/pesce3_dx.png"));
Fishs.push(new FishObject(0, 0, 0.2, 0.5, "https://s30.postimg.org/62lb9bfwx/pesce4_sx.png",
"https://s28.postimg.org/kt5m4ea65/pesce4_dx.png"));
Fishs.push(new FishObject(0, 0, 0.7, 0.1, "https://s18.postimg.org/q5sq0saex/pesce5_sx.png",
"https://s18.postimg.org/uqnwe2vex/pesce5_dx.png"));
setInterval(function() {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(backgroundImage, 0, 0);
for (var i = 0; i < Fishs.length; i++) {
var fishObject = Fishs[i];
fishObject.Draw(ctx);
fishObject.Update(ctx);
}
}, (1000 / 60)); // 60 FPS (frames per second)