使用帆布怎么将文本转换为粒子效果?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
<强>实现原理强>
总的来说要做出将文本变成粒子展示的效果其实很简单,实现的原理就是使用两张画布,一张是用户看不到的画布,用来绘制文本;另一张是用户看到的画布,用来根据一个的文本数据来生成粒子。直观表示如图:
<强>创建离屏帆布强>
HTML只需要放置主画布即可:
& lt; !——, HTML 结构,——比; & lt; html> & lt; head> ,,… & lt;/head> & lt; body> & lt;才能canvas id=爸?祝辞& lt;/canvas> & lt;/body> & lt;/html>
然后创建一个离屏画布,并绘制文本:
const WIDTH =, window.innerWidth; const HEIGHT =, window.innerHeight; const offscreenCanvas =, document.createElement(& # 39;帆布# 39;); const offscreenCtx =, offscreenCanvas.getContext (& # 39; 2 d # 39;); 时间=offscreenCanvas.width 宽度; offscreenCanvas.height ,=,高度; 时间=offscreenCtx.font & # 39; 100 px PingFang sc # 39;; 时间=offscreenCtx.textAlign & # 39;中心# 39;; 时间=offscreenCtx.baseline & # 39;中间# 39;; offscreenCtx.fillText(& # 39;你好# 39;,,WIDTH /, 2, HEIGHT /, 2),
这时页面上什么也没有发生,但实际上可以想象在离屏画布上,此时应该如图所示:
<强>核心方法getImageData 强>
使用帆布的getImageData方法,可以获取一个<代码> ImageData> 代码对象,这个对象用来描述帆布指定区域内的像素数据。也就是说,我们可以获取“你好”这个文本每个像素点的位置和颜色,也就可以在指定位置生成粒子,最后形成的效果就是粒子拼凑成文本了。
要获取像素信息,需要使用<代码> ImageData> 代码对象的<代码> 代码>数据属性,它将所有像素点的rgba值铺开成了一个数组,每个像素点有rgba四个值,这个数组的个数也就是<代码>像素点数量* 4> 代码。
假设我选取了一个<代码> 3 * 4> 代码区域,那么一共12个像素点,每个像素点有rgba四个值,所以数据这个数组就会有<代码> 12 * 4=48 代码>个元素。
如果打印出数据,可以看到即从左往右,从上往下排列这些像素点的rgba。
当然我们要获取的区域必须要包含文本,所以应该获取整个离屏画布的区域:
const imgData =, offscreenCtx.getImageData(0, 0,宽度,高度). data;
<强>生成粒子强>
拿到ImageData后,通过遍历数据数组,可以判断在离屏画布的画布中,哪些点是有色彩的(处于文本中间),哪些点是没有色彩的(不在文本上),把那些有色彩的像素位置记下来,然后在主画布上生成粒子,就好了。
首先创建一下粒子类:
class Particle { ,,,constructor (options =, {}), { ,,,,,,,const {, x =, 0,, y =, 0,, color =, & # 39; # fff& # 39;,, radius =, 5},=,选项; ,,,,,,,this.radius =,半径; ,,,,,,,this.x =, x; ,,,,,,,this.y =, y; ,,,,,,,this.color =,颜色; ,,,} ,,,draw (ctx), { ,,,,,,,ctx.beginPath (); ,,,,,,,ctx.arc (this.x, this.y,, this.radius,, 0,, 2, *, Math.PI,,假); ,,,,,,,ctx.fillStyle =, this.color; ,,,,,,,ctx.fill (); ,,,,,,,ctx.closePath (); ,,,} }
遍历数据,我们可以根据透明度,也就是rgba中的第四个元素是否不为0来判断该像素是否在文本中。
const particles =, []; const skip =, 4; 时间=for (var y 0;, y & lt;,高度;,y +=,跳过),{ ,,,for (var x =, 0;, x & lt;,宽度;,x +=,跳过),{ ,,,,,,,var opacityIndex =,(时间+ x y *,宽度),*,4,+,3; ,,,,,,,if (imgData [opacityIndex],祝辞,0),{ ,,,,,,,,,,,particles.push (new 粒子({ ,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,半径:,1, ,,,,,,,,,,,,,,,颜色:,& # 39;# 2 ea9df& # 39; ,,,,,,,,,,,})); ,,,,,,,} ,,,} null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null使用帆布怎么将文本转换为粒子效果