咨询:如何实现水滴状鼠标光标背景放大扭曲效果
咨询:如何实现水滴状鼠标光标背景放大扭曲效果
嗨,你已经把跟随鼠标的圆圈动画做得很到位啦!要实现那种类似水滴的背景放大+边缘扭曲效果,其实核心思路是让每个圆圈都“显示”页面背景的对应区域,再通过CSS调整放大和扭曲感,我来给你一步步改代码:
第一步:修改CSS,让圆圈变成“背景窗口”
首先把圆圈的纯色背景去掉,换成和页面一致的背景样式,同时设置背景放大来实现中心放大效果,再添加滤镜模拟水滴边缘的模糊扭曲感:
body { width: 100%; min-height: 100vh; position: relative; background-image: linear-gradient( #553c9a 0%, #553c9a 20%, #b393d3 20%, #b393d3 40%, #553c9a 40%, #553c9a 60%, #b393d3 60%, #b393d3 80%, #553c9a 80%, #553c9a 100% ); background-size: cover; background-attachment: fixed; } .circle { height: 75px; width: 75px; border-radius: 50%; position: fixed; /* 关键:和页面同背景,固定定位保证背景同步 */ background-image: linear-gradient( #553c9a 0%, #553c9a 20%, #b393d3 20%, #b393d3 40%, #553c9a 40%, #553c9a 60%, #b393d3 60%, #b393d3 80%, #553c9a 80%, #553c9a 100% ); background-size: 200% 200%; /* 放大背景,实现中心放大效果 */ background-attachment: fixed; top: 0; left: 0; pointer-events: none; z-index: 99999999; /* 模拟水滴边缘的轻微扭曲模糊 */ filter: drop-shadow(0 0 2px rgba(0,0,0,0.2)) contrast(1.1); }
第二步:修改JS,同步圆圈背景与鼠标位置
要让圆圈内显示鼠标对应的背景区域,需要在动画逻辑里计算每个圆圈的背景定位,让它和鼠标位置精准对应:
const coords = { x: 0, y: 0 }; const circles = document.querySelectorAll(".circle"); circles.forEach(function (circle) { circle.x = 0; circle.y = 0; }); window.addEventListener("mousemove", function(e){ coords.x = e.clientX; coords.y = e.clientY; }); function animateCircles() { let x = coords.x; let y = coords.y; let speed = 0.8; circles.forEach(function (circle, index) { // 让圆圈中心对齐鼠标(宽高75,所以偏移一半) circle.style.left = x - 37.5 + "px"; circle.style.top = y - 37.5 + "px"; circle.x = x; circle.y = y; // 保留你原来的缩放逻辑 circle.style.scale = ((1.5 - 1) * (index - 1) / (20 - 1)) + 1; // 关键:计算背景位置,让圆圈内显示鼠标对应的背景区域 const bgX = (x / window.innerWidth) * 100 - 50; const bgY = (y / window.innerHeight) * 100 - 50; circle.style.backgroundPosition = `${bgX}% ${bgY}%`; const nextCircle = circles[index + 1] || circles[0]; x += (nextCircle.x - x) * speed; y += (nextCircle.y - y) * speed; }); requestAnimationFrame(animateCircles); } animateCircles();
第三步:优化层级扭曲感(可选)
如果想要更贴近水滴的层次感,可以给不同位置的圆圈调整背景放大比例和滤镜强度,越外层的圆圈放大稍弱、边缘模糊更强:
// 在forEach循环里添加这两行 circle.style.backgroundSize = `${200 - index * 5}% ${200 - index * 5}%`; circle.style.filter = `drop-shadow(0 0 ${1 + index * 0.1}px rgba(0,0,0,0.2)) contrast(${1.1 + index * 0.02})`;
这样调整后,每个圆圈就会像水滴一样,中心放大对应位置的背景,边缘带有自然的扭曲模糊感,和你想要的效果就很接近啦!
备注:内容来源于stack exchange,提问作者Ludovic Commanay
相关产品推荐
相关产品推荐

