首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何优化这个js动画?

我如何优化这个js动画?
EN

Stack Overflow用户
提问于 2022-09-28 06:14:45
回答 1查看 33关注 0票数 0

我一直试图建立这个动画与三个棕榈叶轻轻摇摆作为一个网站的背景,但它需要尽可能顺利运行,而不干扰页面加载时间太多。我对js非常陌生,所以我目前的代码可能不是最优的,

因此,我想知道我是否能得到一些建议,说明如何优化代码,使其运行得更好更快。你认为如何?

这是现在的代码

代码语言:javascript
复制
  const background = document.querySelector(".leaf-background");

  const leafs1 = document.createElement("div");
  const leafs2 = document.createElement("div");
  const leafs3 = document.createElement("div");

  leafs1.classList.add("leaf-1");
  leafs2.classList.add("leaf-2");
  leafs3.classList.add("leaf-3");

  background.appendChild(leafs1);
  background.appendChild(leafs2);
  background.appendChild(leafs3);

  let animateLeafs1 = () => {
    anime({
      targets: ".leaf-1",
      rotateZ: () => {
        return anime.random(-5, 5);
      },
      rotateX: () => {
        return anime.random(-30, 30);
      },
      easing: "linear",
      duration: 3000,
      complete: animateLeafs1
    });

  };
  animateLeafs1();

  let animateLeafs2 = () => {
    anime({
      targets: ".leaf-2",
      //rotateZ: () => {
      //  return anime.random(-5, 5);
      //},
      rotateX: () => {
        return anime.random(40, -40);
      },
      easing: "linear",
      duration: 4000,
      complete: animateLeafs2
    });

  };
  animateLeafs2();

  let animateLeafs3 = () => {

    anime({
      targets: ".leaf-3",
      rotateZ: () => {
        return anime.random(-2, 2);
      },
      rotateX: () => {
        return anime.random(30, -30);
      },
      easing: "linear",
      duration: 4000,
      complete: animateLeafs3
    });

  };
  animateLeafs3();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-28 09:43:01

这个有用吗?我甚至不能测试它

代码语言:javascript
复制
        const background = document.querySelector(".leaf-background");
        const leafArray = []
      // array starts from 0
        for(var i=0; i<3;i++){
          leafArray[i]= document.createElement("div");
          // remember that classes start from 0 ---> leaf-0, leaf-1 , leaf-2
          leafArray[i].classList.add("leaf-" + i);
          // add a common class for selector
          leafArray[i].classList.add("generalLeafs")
          background.appendChild(leafArray[i]);
        }
        console.log(leafArray);
        let animateLeafs = () => {
          anime({
            targets: ".generalLeafs",
            rotateZ: () => {
              return anime.random(-5, 5);
            },
            rotateX: () => {
              return anime.random(-30, 30);
            },
            easing: "linear",
            duration: 3000,
            complete: animateLeafs
          });
      
        };
        animateLeafs();

从0开始类名

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73876925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档