图片聚光效果(Image Spotlight Effect)是一种视觉效果,通过突出显示图像的特定区域来吸引用户的注意力。这种效果通常用于引导用户关注图像中的重要部分,或者在交互式应用中作为用户操作的反馈。
以下是一个使用JavaScript和CSS实现圆形聚光效果的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Spotlight Effect</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="image-container">
<img src="your-image.jpg" alt="Sample Image">
<div class="spotlight"></div>
</div>
<script src="script.js"></script>
</body>
</html>.image-container {
position: relative;
width: 80%;
margin: 0 auto;
}
.image-container img {
width: 100%;
display: block;
}
.spotlight {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background: rgba(255, 255, 255, 0.5);
border-radius: 50%;
pointer-events: none;
}document.addEventListener('DOMContentLoaded', () => {
const spotlight = document.querySelector('.spotlight');
const container = document.querySelector('.image-container');
container.addEventListener('mousemove', (e) => {
const rect = container.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
spotlight.style.left = `${x - spotlight.offsetWidth / 2}px`;
spotlight.style.top = `${y - spotlight.offsetHeight / 2}px`;
});
container.addEventListener('mouseleave', () => {
spotlight.style.left = '50%';
spotlight.style.top = '50%';
});
});requestAnimationFrame来优化动画效果,减少DOM操作。let rafId;
container.addEventListener('mousemove', (e) => {
if (rafId) cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(() => {
const rect = container.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
spotlight.style.left = `${x - spotlight.offsetWidth / 2}px`;
spotlight.style.top = `${y - spotlight.offsetHeight / 2}px`;
});
});window.devicePixelRatio来调整聚光效果的大小和位置。const dpr = window.devicePixelRatio || 1;
container.addEventListener('mousemove', (e) => {
const rect = container.getBoundingClientRect();
const x = (e.clientX - rect.left) * dpr;
const y = (e.clientY - rect.top) * dpr;
spotlight.style.left = `${x / dpr - spotlight.offsetWidth / 2}px`;
spotlight.style.top = `${y / dpr - spotlight.offsetHeight / 2}px`;
});通过以上方法,可以实现一个简单且高效的图片聚光效果,并解决一些常见的问题。
没有搜到相关的文章