加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

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

发布时间:2020-05-11 07:01:54 所属栏目:编程 来源:站长网
导读:副问题#e# 通过粒子来绘制文本让人感受很故意思,共同粒子的行为更会让这个结果越发酷炫。本文先容在 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 中滑腻轮回改变,很轻易让人遐想到三角函数,如:

横轴应该是与时刻相干,可以再维护一个变量每次挪用 update 的时辰举办加操纵,简朴做也可以直接用时刻戳来举办计较。update 要领示譬喻下:

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

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

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读