神奇的 3D 磨砂玻璃透视效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/919d180302d504f713ed28f4fdcb013e.jpeg#pic_center)
- 毛玻璃磨砂效果
- 卡片的 3D 旋转跟随效果
- 整体透明度和磨砂感、以及卡片的 3D 形态会随着用户移动鼠标而进行动态变化
直接上代码
<body>
<div id="element"></div>
</body>
body {
padding:0;
margin: 0;
width: 100vw;
height: 100vh;
background: url(https://picsum.photos/id/242/1920/1080) 100% 100%;
background-size: cover;
transform-style: preserve-3d;
display: flex;
align-items: center;
justify-content: center;
}
div {
width: 600px;
height: 300px;
backdrop-filter: blur(15px);
background: linear-gradient(var(--angle), rgba(255, 255, 255, 0.1), rgba(0, 0, 0, 0.5));
mask: linear-gradient(var(--angle), rgba(255, 255, 255, .5), #fff);
transition: all 0.3s, --angle 0.3s;
}
const multiple = 25;
const mouseOverContainer = document.getElementsByTagName("body")[0];
const element = document.getElementById("element");
function transformElement(x, y) {
const box = element.getBoundingClientRect();
const calcX = -(y - box.y - (box.height / 2)) / multiple;
const calcY = (x - box.x - (box.width / 2)) / multiple;
let angle = Math.floor(getMouseAngle((y - box.y - (box.height / 2)), (x - box.x - (box.width / 2))));
element.style.transform = "rotateX("+ calcX +"deg) " + "rotateY("+ calcY +"deg)";
element.style.setProperty("--angle", `${-angle}deg`);
}
function getMouseAngle(x, y) {
const radians = Math.atan2(y, x);
let angle = radians * (180 / Math.PI);
if (angle < 0) {
angle += 360;
}
return angle;
}
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)";
});
});