本文展示了使用HarmonyOS实现粒子文字动画效果的方案,核心流程包括:将文字分解为粒子坐标,添加随机运动轨迹,并通过属性动画控制位移和透明度。代码采用TypeScript编写,利用animateTo实现异步动画,配合Friction曲线模拟自然减速效果。关键点包含150个随机粒子初始化、异步动画控制、渐隐效果实现以及物理曲线选择,最终呈现粒子从文字形态扩散消失的视觉特效。
实现的流程图如下

实现思路
-
将文字分解为粒子坐标
-
为粒子添加随机运动轨迹
-
使用属性动画控制位移和透明度
// ParticleText.ets
import { Curve, animateTo } from '@ohos.animation';
@Entry
@Component
struct ParticleText {
@State particles: Array<{ x: number, y: number, dx: number, dy: number, alpha: number }> = [];
aboutToAppear() {
this.initParticles('HarmonyOS', 200, 300);
}
// 初始化粒子
initParticles(text: string, startX: number, startY: number) {
const particles = [];
for (let i = 0; i < 150; i++) {
particles.push({
x: startX + Math.random() * 200,
y: startY + Math.random() * 50,
dx: (Math.random() - 0.5) * 10,
dy: (Math.random() - 0.5) * 10,
alpha: 1
});
}
this.particles = particles;
}
// 启动动画
startAnimation() {
this.particles.forEach((particle, index) => {
animateTo({
duration: 1500,
curve: Curve.Friction,
delay: index * 10,
onFinish: () => {
particle.alpha = 0;
}
}, () => {
particle.x += particle.dx * 30;
particle.y += particle.dy * 30;
});
});
}
build() {
Stack({ alignContent: Alignment.Center }) {
// 粒子绘制
ForEach(this.particles, (item) => {
Circle()
.width(5)
.height(5)
.fill(Color.Blue)
.position({ x: item.x, y: item.y })
.opacity(item.alpha)
})
// 控制按钮
Button('启动动画')
.onClick(() => this.startAnimation())
.margin(20)
.align(Alignment.Bottom)
}
.width('100%')
.height('100%')
.backgroundColor(Color.White)
}
}
关键点解析
-
粒子初始化:创建150个随机位置粒子
-
动画控制:使用animateTo实现异步交互动画
-
渐隐效果:动画结束时设置透明度为0
-
曲线选择:Curve.Friction模拟摩擦减速效果

被折叠的 条评论
为什么被折叠?



