在现代网页设计中,交互动效对于提升用户体验起着重要作用。本文将介绍如何结合 Particles.js 和 GSAP 动画库,创建一个引人注目的粒子动画效果网页。
首先,我们需要创建基本的 HTML 结构,并引入必要的库:
html
DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>粒子动画 + GSAP 效果title>
head>
<body>
<div id="particles-js">div>
<div class="content">
div>
<script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js">script>
body>
html>
关键的 CSS 样式设置:
```css
css
body {
background: #0a192f;
color: #64ffda;
overflow: hidden;
}
#particles-js {
position: absolute;
width: 100%;
height: 100%;
z-index: 1;
}
.content {
position: relative;
z-index: 2;
}
### 3. 粒子效果配置
Particles.js 的核心配置:
```javascript
particlesJS('particles-js', {
particles: {
number: { value: 80 },
color: { value: ['#64ffda', '#FF6B6B', '#4ECDC4'] },
shape: { type: 'circle' },
opacity: {
value: 0.6,
random: true,
anim: { enable: true }
},
size: {
value: 6,
random: true,
anim: { enable: true }
},
move: {
enable: true,
speed: 3
}
},
interactivity: {
detect_on: 'window',
events: {
onhover: {
enable: true,
mode: ['bubble', 'connect']
}
}
}
});
使用 GSAP 创建平滑的入场动画:
window.addEventListener('load', () => {
const timeline = gsap.timeline();
timeline
.to('h1', {
opacity: 1,
y: 0,
duration: 1
})
.to('.description', {
opacity: 1,
y: 0,
duration: 1
}, '-=0.5');
});
创建跟随鼠标的自定义指针:
const cursor = document.querySelector('.cursor');
const follower = document.querySelector('.cursor-follower');
document.addEventListener('mousemove', (e) => {
requestAnimationFrame(() => {
cursor.style.transform = `translate(${e.clientX - 10}px, ${e.clientY - 10}px)`;
follower.style.transform = `translate(${e.clientX - 20}px, ${e.clientY - 20}px)`;
});
});
requestAnimationFrame
优化动画性能pointer-events: none
避免粒子层影响交互z-index
正确管理层级关系function isMobileDevice() {
return (typeof window.orientation !== “undefined”)
|| (navigator.userAgent.indexOf(‘IEMobile’) !== -1)
|| window.matchMedia(“(max-width: 768px)”).matches;
}
问题:初始实现时,粒子层阻挡了页面交互。
解决:为粒子层添加 pointer-events: none
,确保底层元素可交互。
问题:自定义鼠标指针在移动端造成困扰。
解决:通过媒体查询和设备检测,在移动端禁用自定义指针。
问题:动画效果导致页面卡顿。
解决:使用 requestAnimationFrame
和 CSS 硬件加速。
如果觉得这篇文章对你有帮助,欢迎点赞、收藏和评论!