🙆

【GSAP】GSAP Practice【#3 GSAP TO】

2024/11/28に公開

【#3 GSAP TO】

YouTube: https://youtu.be/pm15ftDj_gs
https://youtu.be/pm15ftDj_gs

今回はGSAPの基本的な設定について解説していきます。

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Gsap practice</title>
    <link rel="stylesheet" href="css/main.css" />
  </head>
  <body>
    <div class="section-1">
      <div class="box box-1">gsap.to</div>
      <div class="box box-2">gsap.from</div>
      <div class="box box-3">gsap.fromTo</div>
    </div>
    <div class="section-2">section2</div>

    <script src="https://unpkg.com/lenis@1.1.16/dist/lenis.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/ScrollTrigger.min.js"></script>
    <script src="js/main.js"></script>
  </body>
</html>
css/main.css
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
html,
body {
  width: 100%;
  height: 100%;
}
.section-1,
.section-2 {
  width: 100%;
  height: 100vh;
}
.section-1 {
  background-color: salmon;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.section-2 {
  background-color: skyblue;
}
.box {
  width: 160px;
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}
.box-1 {
  background-color: red;
}
.box-2 {
  background-color: blue;
}
.box-3 {
  background-color: green;
}
js/main.js
// use a script tag or an external JS file
document.addEventListener("DOMContentLoaded", (event) => {
  gsap.registerPlugin(ScrollTrigger);

  // Initialize Lenis
  const lenis = new Lenis();

  // Use requestAnimationFrame to continuously update the scroll
  function raf(time) {
    lenis.raf(time);
    requestAnimationFrame(raf);
  }

  requestAnimationFrame(raf);

  // gsap code here!

  gsap.set(".box-1", {
    x: 300,
  });

  gsap.to(".box-1", {
    x: window.innerWidth - 160,
    duration: 3,
  });

  gsap.from(".box-2", {
    x: 500,
    duration: 3,
  });

  gsap.fromTo(
    ".box-3",
    {
      x: 500,
    },
    {
      x: 200,
      duration: 3,
    }
  );

  // windowResize(() => {
  //   gsap.to(".box-1", {
  //     x: window.innerWidth - 160,
  //     duration: 3,
  //   });
  // });
});

// let timer;

// const windowResize = (fn) => {
//   window.addEventListener("resize", () => {
//     clearTimeout(timer);
//     timer = setTimeout(() => {
//       console.log("resize");
//       fn();
//     }, 500);
//   });
// };

Discussion