I’ve been trying to build this animation with three palm leaves gently swaying as a background for a website, but it needs to run as smoothly as possible without messing with the page loading time too much. I’m pretty new to js so the code I’ve got at the moment is probably not optimal,
Therefore I am asking if I could get some suggestions on how I could optimize the code to make it run better and faster. What do you think?
this is the code right now
JavaScript
x
66
66
1
const background = document.querySelector(".leaf-background");
2
3
const leafs1 = document.createElement("div");
4
const leafs2 = document.createElement("div");
5
const leafs3 = document.createElement("div");
6
7
leafs1.classList.add("leaf-1");
8
leafs2.classList.add("leaf-2");
9
leafs3.classList.add("leaf-3");
10
11
background.appendChild(leafs1);
12
background.appendChild(leafs2);
13
background.appendChild(leafs3);
14
15
let animateLeafs1 = () => {
16
anime({
17
targets: ".leaf-1",
18
rotateZ: () => {
19
return anime.random(-5, 5);
20
},
21
rotateX: () => {
22
return anime.random(-30, 30);
23
},
24
easing: "linear",
25
duration: 3000,
26
complete: animateLeafs1
27
});
28
29
};
30
animateLeafs1();
31
32
let animateLeafs2 = () => {
33
anime({
34
targets: ".leaf-2",
35
//rotateZ: () => {
36
// return anime.random(-5, 5);
37
//},
38
rotateX: () => {
39
return anime.random(40, -40);
40
},
41
easing: "linear",
42
duration: 4000,
43
complete: animateLeafs2
44
});
45
46
};
47
animateLeafs2();
48
49
let animateLeafs3 = () => {
50
51
anime({
52
targets: ".leaf-3",
53
rotateZ: () => {
54
return anime.random(-2, 2);
55
},
56
rotateX: () => {
57
return anime.random(30, -30);
58
},
59
easing: "linear",
60
duration: 4000,
61
complete: animateLeafs3
62
});
63
64
};
65
animateLeafs3();
66
Advertisement
Answer
does this work? i cant even test it
JavaScript
1
28
28
1
const background = document.querySelector(".leaf-background");
2
const leafArray = []
3
// array starts from 0
4
for(var i=0; i<3;i++){
5
leafArray[i]= document.createElement("div");
6
// remember that classes start from 0 ---> leaf-0, leaf-1 , leaf-2
7
leafArray[i].classList.add("leaf-" + i);
8
// add a common class for selector
9
leafArray[i].classList.add("generalLeafs")
10
background.appendChild(leafArray[i]);
11
}
12
console.log(leafArray);
13
let animateLeafs = () => {
14
anime({
15
targets: ".generalLeafs",
16
rotateZ: () => {
17
return anime.random(-5, 5);
18
},
19
rotateX: () => {
20
return anime.random(-30, 30);
21
},
22
easing: "linear",
23
duration: 3000,
24
complete: animateLeafs
25
});
26
27
};
28
animateLeafs();
start you class names from 0