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 (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |