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 中平滑循环改变,很容易让人联想到三角函数,如: 横轴应该是与时间相关,可以再维护一个变量每次调用 update 的时候进行加操作,简单做也可以直接用时间戳来进行计算。update 方法示例如下: update () { this.dynamicRadius = 3 + 2 * Math.sin(new Date() / 1000 % 1000 * this.radius); } 完整代码见 02-text-to-particles-with-size-changing (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |