文字粒子化效果

效果说明

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

核心实现

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

相关推荐
计算机魔术师19 分钟前
我看了 Hugging Face 的 Daily Papers,发现这件事
前端
yu俞娥宝1 小时前
Codex官网前端可抄吗?技术拆解、风险边界与合规借鉴方案
前端
捧 花1 小时前
FastAPI 基础语法:从一个完整接口理解 Web API 的设计
前端·python·fastapi·middleware
Hilaku2 小时前
一行 CSS 新特性干掉 20 行 JavaScript ?
前端·javascript·程序员
风月说与山鬼2 小时前
JS闭包详解
开发语言·javascript
JarvanMo2 小时前
AI 写代码暴增 161 倍,移动开发有没有变得更差?
前端
梦曦i2 小时前
RouterLink v2.5.0:H5端原生能力全面回归
前端·uni-app
小林ixn2 小时前
React + Zustand + JWT:从零实现登录鉴权与请求拦截
前端·react.js·前端框架
葡萄城技术团队2 小时前
下拉多选类型单元格:在 SpreadJS 里接入 xm\-select
前端
粥里有勺糖3 小时前
视野修炼-技术周刊第130期 | 光影效果
前端·javascript·github