3D卡片光效

实现效果

实现注意

  1. mix-blend-mode: color-dodge;
  2. const calcX = ((y - box.y - box.height / 2) / multiple) * -1;

实现代码

<div id="element"></div>
body {
  height: 100vh;
  display: flex;
  transform-style: preserve-3d;
  perspective: 500px;
  cursor: pointer;
}

#element {
  --pre: 30%;
  margin: auto;
  width: 270px;
  height: 375px;
  border-radius: 10px;
  transform-style: preserve-3d;
  transition: all 0.1s;
  background-image: url("../pic/下载.png");
  overflow: hidden;
}
#element::after {
  position: absolute;
  content: "";
  inset: 0;
  background-image: url("../pic/2786177369-f0fc6ca57c9fc19d.webp");
  mix-blend-mode: color-dodge;
}
#element::before {
  content: "";
  position: absolute;
  inset: 0;
  background: linear-gradient(
    115deg,
    transparent 0%,

    rgba(255, 255, 255, 0.5) var(--pre),
    rgba(0, 0, 0, 0.5) calc(var(--pre) + 25%),
    rgba(255, 255, 255, 0.5) calc(var(--pre) + 50%),
    transparent 100%
  );
  mix-blend-mode: color-dodge;
}
#element:hover::after,
#element:hover::before {
  display: block;
}
const multiple = 20;
const mouseOverContainer = document.getElementsByTagName("body")[0];
const element = document.getElementById("element");

function transformElement(x, y) {
  const box = element.getBoundingClientRect();
  const calcY = (x - box.x - box.width / 2) / multiple;
  const calcX = ((y - box.y - box.height / 2) / multiple) * -1;
  const percentage = parseInt(((x - box.x) / box.width) * 1000) / 10;

  element.style.transform = `rotateX(${calcX}deg) rotateY(${calcY}deg)`;
  element.style.setProperty("--pre", `${percentage}%`);
}

mouseOverContainer.addEventListener("mousemove", (e) => {
  window.requestAnimationFrame(function () {
    transformElement(e.clientX, e.clientY);
  });
});
mouseOverContainer.addEventListener("mouseleave", (e) => {
  window.requestAnimationFrame(function () {
    element.style.transform = "rotateX(0) rotateY(0)";
  });
});

背景图片

posted @ 2024-03-24 11:33  codejnp  阅读(9)  评论(0编辑  收藏  举报