javascript 光标移动动画

lx0bsm1f  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(90)

问题是我在复制我在页面上看到的动画时遇到了一个小问题。我已经尝试了几种方法,并确定了我目前的实现。
我试过用css和js制作动画,结果不像我复制的页面那么流畅。这是我试图复制https://www.myorthos.com/的着陆页动画
这是我的代码

const images = document.querySelectorAll(".image");
const container = document.querySelector(".image-container");
let animationFrameId = null;

// Listen for cursor movement
container.addEventListener("mousemove", (e) => {
  const centerX = container.clientWidth / 2;
  const centerY = container.clientHeight / 2;

  if (animationFrameId !== null) {
    cancelAnimationFrame(animationFrameId);
  }
  // Move images smoothly
  animationFrameId = requestAnimationFrame(() => {
    images.forEach((image, index) => {
      const xOffset = (centerX - e.clientX) / 10;
      const yOffset = (centerY - e.clientY) / 10;

      // Apply a slight delay to each img when moving
      const delay = index * 50;

      setTimeout(() => {
        if (!image.classList.contains("hovered")) {
          image.style.transform = `translate(${xOffset}px, ${yOffset}px)`;
        }
      }, delay);
    });
  });
});
// When cursor leaves the container
container.addEventListener("mouseout", () => {
  // Reset the img positions when the cursor leaves the container
  if (animationFrameId !== null) {
    cancelAnimationFrame(animationFrameId);
  }
  images.forEach((image) => {
    image.style.transform = "translate(0, 0)";
  });
});
body {
  background-color: azure;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

h5 {
  text-align: center;
}

img {
  width: 100px;
  height: 100px;
}

.image-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.image {
  position: absolute;
  transition: .8s linear;
}

.image:hover {
  transform: translate(0, 0) !important;
}

#image1 {
  left: 20%;
  top: 20%;
}

#image2 {
  left: 27%;
  bottom: 20%;
}

#image3 {
  left: 60%;
  top: 60%;
}

#image4 {
  right: 20%;
  top: 20%;
}
<h5>PRACTICE TESTING ANIMATIONS</h5>

<div class="image-container">
  <img src="image1.jpg" class="image" id="image1">
  <img src="image2.jpg" class="image" id="image2">
  <img src="image3.jpg" class="image" id="image3">
  <img src="image4.jpg" class="image" id="image4">
</div>
vfh0ocws

vfh0ocws1#

原来的是使用(指数)缓和(和更精确)的动画。事

function easeOutExpo (t, b, c, d) {
    return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
}

可以做到这一点。查看this作为JS轻松函数的重要资源。

相关问题