文字粒子化效果

效果说明

本案例实现了一个文字粒子化的动画效果。将文字转换为由多个彩色粒子组成的形状,粒子会从随机位置移动到文字轮廓上,形成动态的组合效果。

核心实现

1. 粒子系统设计

每个粒子都包含目标位置和当前位置,通过线性插值实现平滑移动:

javascript 复制代码
class Particle {
    constructor(x, y) {
        // 目标位置(文字轮廓上的点)
        this.targetX = x;
        this.targetY = y;
        
        // 当前位置(随机分布在画布上)
        this.currentX = Math.random() * canvas.width;
        this.currentY = Math.random() * canvas.height;
        
        this.speed = 0.05;  // 移动速度
        this.color = `hsl(${Math.random() * 360}, 50%, 50%)`; // 随机颜色
    }
}

2. 文字像素采样

通过获取文字的像素数据来确定粒子位置:

javascript 复制代码
// 绘制文字
ctx.fillText(text, canvas.width / 2, canvas.height / 2);

// 获取像素数据
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;

// 根据像素创建粒子
for (let y = 0; y < canvas.height; y += 4) {
    for (let x = 0; x < canvas.width; x += 4) {
        const index = (y * canvas.width + x) * 4;
        const alpha = data[index + 3];  // 获取alpha通道值
        
        if (alpha > 128) {
            particles.push(new Particle(x, y));
        }
    }
}

3. 平滑移动实现

使用线性插值实现粒子的平滑移动:

javascript 复制代码
update() {
    // 新位置 = 当前位置 + (目标位置 - 当前位置) * 速度
    this.currentX += (this.targetX - this.currentX) * this.speed;
    this.currentY += (this.targetY - this.currentY) * this.speed;
}

关键参数说明

  • speed: 粒子移动速度(0-1),值越大移动越快
  • size: 粒子大小
  • 采样间隔(4像素): 控制粒子数量
  • 背景透明度(0.1): 控制拖尾效果

Demo

相关推荐
望获linux1 分钟前
【Linux基础知识系列:第一百五十九篇】磁盘健康监测:smartctl
linux·前端·数据库·chrome·python·操作系统·软件
十一吖i1 小时前
vue3表格显示隐藏列全屏拖动功能
前端·javascript·vue.js
冰暮流星3 小时前
css之线性渐变
前端·css
徐同保3 小时前
tailwindcss暗色主题切换
开发语言·前端·javascript
mapbar_front3 小时前
大厂精英为何在中小公司水土不服?
前端
生莫甲鲁浪戴3 小时前
Android Studio新手开发第二十七天
前端·javascript·android studio
细节控菜鸡5 小时前
【2025最新】ArcGIS for JS 实现随着时间变化而变化的热力图
开发语言·javascript·arcgis
2501_916008895 小时前
Web 前端开发常用工具推荐与团队实践分享
android·前端·ios·小程序·uni-app·iphone·webview
SkylerHu6 小时前
前端代码规范:husky+ lint-staged+pre-commit
前端·代码规范
菜鸟una6 小时前
【微信小程序 + 消息订阅 + 授权】 微信小程序实现消息订阅流程介绍,代码示例(仅前端)
前端·vue.js·微信小程序·小程序·typescript·taro·1024程序员节