DDR爱好者之家 Design By 杰米

本文介绍了Canvas 文本转粒子效果的实现代码,分享给大家,希望对大家有所帮助,具体如下:

Canvas 文本转粒子效果的实现代码

通过粒子来绘制文本让人感觉很有意思,配合粒子的运动更会让这个效果更加酷炫。本文介绍在 canvas 中通过粒子来绘制文本的方法。

实现原理

总的来说要做出将文本变成粒子展示的效果其实很简单,实现的原理就是使用两张 canvas,一张是用户看不到的 A canvas,用来绘制文本;另一张是用户看到的 B canvas,用来根据 A 的文本数据来生成粒子。直观表示如图:

Canvas 文本转粒子效果的实现代码

创建离屏 canvas

HTML 只需要放置主 canvas 即可:

<!-- HTML 结构 -->
<html>
<head>
  ...
</head>
<body>
  <canvas id="stage"></canvas>
</body>
</html>

然后创建一个离屏 canvas,并绘制文本:

const WIDTH = window.innerWidth;
const HEIGHT = window.innerHeight;

const offscreenCanvas = document.createElement('canvas');
const offscreenCtx = offscreenCanvas.getContext('2d');

offscreenCanvas.width = WIDTH;
offscreenCanvas.height = HEIGHT;

offscreenCtx.font = '100px PingFang SC';
offscreenCtx.textAlign = 'center';
offscreenCtx.baseline = 'middle';
offscreenCtx.fillText('Hello', WIDTH / 2, HEIGHT / 2);

这时页面上什么也没有发生,但实际上可以想象在离屏 canvas 上,此时应该如图所示:

Canvas 文本转粒子效果的实现代码

核心方法 getImageData

使用 canvas 的 getImageData 方法,可以获取一个 ImageData 对象,这个对象用来描述 canvas 指定区域内的像素数据。也就是说,我们可以获取 “Hello” 这个文本每个像素点的位置和颜色,也就可以在指定位置生成粒子,最后形成的效果就是粒子拼凑成文本了。

要获取像素信息,需要使用 ImageData 对象的 data 属性,它将所有像素点的 rgba 值铺开成了一个数组,每个像素点有 rgba 四个值,这个数组的个数也就是 像素点数量 * 4

假设我选取了一个 3 * 4 区域,那么一共 12 个像素点,每个像素点有 rgba 四个值,所以 data 这个数组就会有 12 * 4 = 48 个元素。

Canvas 文本转粒子效果的实现代码

如果打印出 data,可以看到即从左往右,从上往下排列这些像素点的 rgba。

Canvas 文本转粒子效果的实现代码

当然我们要获取的区域必须要包含文本,所以应该获取整个离屏 canvas 的区域:

const imgData = offscreenCtx.getImageData(0, 0, WIDTH, HEIGHT).data;

生成粒子

拿到 ImageData 后,通过遍历 data 数组,可以判断在离屏 canvas 的画布中,哪些点是有色彩的(处于文本中间),哪些点是没有色彩的(不在文本上),把那些有色彩的像素位置记下来,然后在主 canvas 上生成粒子,就 ok 了。

首先创建一下粒子类:

class Particle {
    constructor (options = {}) {
        const { x = 0, y = 0, color = '#fff', radius = 5} = options;
        this.radius = radius;
        this.x = x;
        this.y = y;
        this.color = color;
    }

    draw (ctx) {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.closePath();
    }
}

遍历 data,我们可以根据透明度,也就是 rgba 中的第四个元素是否不为 0 来判断该像素是否在文本中。

const particles = [];
const skip = 4;
for (var y = 0; y < HEIGHT; y += skip) {
    for (var x = 0; x < WIDTH; x += skip) {
        var opacityIndex = (x + y * WIDTH) * 4 + 3;
        if (imgData[opacityIndex] > 0) {
            particles.push(new Particle({
                x,
                y,
                radius: 1,
                color: '#2EA9DF'
            }));
        }
    }
}

我们用 particles 数组来存放所有的粒子,这里的 skip 的作用是遍历的步长,如果我们一个像素一个像素地扫,那么最后拼凑文本的粒子将会非常密集,增大这个值,最后产生的粒子就会更稀疏。

最后在创建主 canvas 并绘制即可:

const canvas = document.querySelector('#stage');
canvas.width = WIDTH;
canvas.height = HEIGHT;
const ctx = canvas.getContext('2d');

for (const particle of particles) {
    particle.draw(ctx);
}

效果如下:

Canvas 文本转粒子效果的实现代码

完整代码见01-basic-text-to-particles

添加效果

了解实现原理之后,其实其他的就都是给粒子添加一些动效了。首先可以让粒子有一些随机的位移,避免看上去过于整齐。

const particles = [];
const skip = 4;
for (var y = 0; y < HEIGHT; y += skip) {
    for (var x = 0; x < WIDTH; x += skip) {
        var opacityIndex = (x + y * WIDTH) * 4 + 3;
        if (imgData[opacityIndex] > 0) {
            // 创建粒子时加入随机位移
            particles.push(new Particle({
                x: x + Math.random() * 6 - 3,
                y: y + Math.random() * 6 - 3,
                radius: 1,
                color: '#2EA9DF'
            }));
        }
    }
}

效果如下:

Canvas 文本转粒子效果的实现代码

如果想实现变大的效果,如:

Canvas 文本转粒子效果的实现代码

这种要怎么实现呢,首先需要随机产生粒子的大小,这只需要在创建粒子时对 radius 进行 random 即可。另外如果要让粒子半径动态改变,那么需要区分开粒子的渲染半径和初始半径,并使用 requestAnimationFrame 进行动画渲染:

class Particle {
    constructor (options = {}) {
        const { x = 0, y = 0, color = '#fff', radius = 5} = options;
        this.radius = radius;
        // ...
        this.dynamicRadius = radius; // 添加 dynamicRadius 属性
    }

    draw (ctx) {
        // ...
        ctx.arc(this.x, this.y, this.dynamicRadius, 0, 2 * Math.PI, false); // 替换为 dynamicRadius
        // ...
    }
    
    update () {
        // TODO
    }
}

requestAnimationFrame(function loop() {
    requestAnimationFrame(loop);

    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, WIDTH, HEIGHT);

    for (const particle of particles) {
        particle.update();
        particle.draw(ctx);
    }
});

那么关键就在于粒子的 update 方法要如何实现了,假设我们想让粒子半径在 1 到 5 中平滑循环改变,很容易让人联想到三角函数,如:

Canvas 文本转粒子效果的实现代码

横轴应该是与时间相关,可以再维护一个变量每次调用 update 的时候进行加操作,简单做也可以直接用时间戳来进行计算。update 方法示例如下:

update () {
    this.dynamicRadius = 3 + 2 * Math.sin(new Date() / 1000 % 1000 * this.radius);
}

完整代码见 02-text-to-particles-with-size-changing

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米