I am animating divs'. The animation is very simply moving each div along x and y axis. I am randomly setting the x and y axis value using javascript. I want the animation to be bound only inside the its containing element.
But despite getting height and width using clientHeight & clientWidth in javascript. The animation is getting out the container.Animation is done using Anime.js
I have put all required code.
JAVASCRIPT:
//function to create div and insert it to DOM
function domDiv(count, element, className, elementId) {
let i = 0;
while (i != count) {
let div1 = document.createElement(element);
div1.setAttribute('class', className);
document.getElementById(elementId).appendChild(div1);
i++;
}
}
//function to generate random numbers bounded with container's height and width
function seed(property) {
let ranNum;
if (property == 'H') {
let height = document.getElementById('parent1').clientHeight;
ranNum = Math.floor((Math.random() * height) + 1);
console.log("H: ", height);
console.log("ranNum ", ranNum);
return ranNum;
}
else {
let width = document.getElementById('parent1').clientWidth;
ranNum = Math.floor((Math.random() * width) + 1);
console.log("W: ", width);
console.log("ranNum ", ranNum);
return ranNum;
}
}
//animation function, animation done using anime.js
function randomValues() {
anime({
targets: '#parent1 .divs1',
translateX: function () {
return anime.random(seed('W'), seed('W'));
},
translateY: function () {
return anime.random(seed('H'), seed('H'));
},
scale: [
{ value: .1, easing: 'easeOutSine', duration: 500 },
{ value: 1, easing: 'easeInOutQuad', duration: 1200 }
],
delay: anime.stagger(200, { grid: [14, 5], from: 'center' }),
duration: 800,
easing: 'easeInOutSine',
complete: randomValues
});
}
//execution starts from here or main control takes place below
domDiv(50, 'div', 'divs1', 'parent1');
randomValues();
HTML:
<body>
<section id="parent1"></section>
</body>
CSS:
#parent1 {
width: 100vw;
height: 100vh;
/* padding: 50px; */
display: grid;
grid-template-columns: repeat(5, 1fr);
justify-items: center;
border: solid red 2px;
}
.divs1 {
margin: 5px;
width: 3vw;
height: 3vw;
}
.divs1:nth-child(odd) {
background-color: yellow;
border-radius: 50%;
}
.divs1:nth-child(even) {
background-color: aquamarine;
border-radius: 50%;
}
Aucun commentaire:
Enregistrer un commentaire