介绍
本篇文章为大家展示了使用帆布怎么实现一个粒子动效,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
<强>绘制刻度强>
此例为小时刻度的绘制:表盘上共有12个小时,Math.PI为180,度,每小时占据30,度;。
.save()表示保存帆布当前环境的状态,在此基础上进行绘制。绘制完成之后,返回之前保存过的路径状态和属性。
分钟刻度同理,改变角度与样式即可。
,,//,小时时间刻度 offscreenCanvasCtx.save才能(); for 才能;(var 小姐:=,0;,小姐:& lt;, 12;,我+ +),{ ,,,offscreenCanvasCtx.beginPath (); ,,,//,刻度颜色 ,,,offscreenCanvasCtx.strokeStyle =, & # 39; # fff& # 39;; ,,,//,刻度宽度 ,,,offscreenCanvasCtx.lineWidth =, 3; ,,,//,每小时占据30,度; ,,,offscreenCanvasCtx.rotate(时间/Math.PI 6); ,,,//,开始绘制的位置 ,,,offscreenCanvasCtx.lineTo (140, 0) ,,,//,结束绘制的位置; ,,,offscreenCanvasCtx.lineTo (120,, 0); ,,,//,绘制路径 ,,,offscreenCanvasCtx.stroke (); ,,} offscreenCanvasCtx.restore才能();
<强>指针指向强>
以秒针为例:获取当前时间的秒数,并计算对应的偏移角度
,, var 你=,new 日期(), ,,,sec =, now.getSeconds (), ,,,min =, now.getMinutes (), ,,,hr =, now.getHours (); hr 才能=,hr 祝辞,12,?,hr 作用;12,:,人力资源; ,,//秒才能针 offscreenCanvasCtx.save才能(); offscreenCanvasCtx.rotate才能(sec *,(时间/Math.PI 30)); ,…… offscreenCanvasCtx.stroke才能();
<强>粒子动效强>
画布可以用来绘制复杂,不规则的动画。粒子特效可以用来实现复杂,随机的动态效果。
粒子,指图像数据<代码> imageData> 代码中的每一个像素点,获取到每个像素点之后,添加属性或事件对区域内的粒子进行交互,达到动态效果。
效果
<强>粒子获取强>
以下图的图片转化为例,该效果是先在画布上渲染图片,然后获取文字所在区域的每个像素点。
let image =, new 图像(); image.src才能=https://www.yisu.com/zixun/? ./图像/logo.png”; 让像素=[];//存储像素数据 让imageData; 的形象。宽度=300; 的形象。身高=300//渲染图片,并获取该区域内像素信息 image.onload=function () { ctx.drawImage(图片,(canvas.width-image.width)/2, (canvas.height-image.height)/2, image.width, image.height); imageData=ctx.getImageData ((canvas.width-image.width)/2, (canvas.height-image.height)/2, image.width, image.height);//获取图表像素信息//绘制图像 };
<>强像素信息强>
图片的大小为300 * 300,共90000个有像素,每个像素占4位,存放rgba数据。
<强>粒子绘制强>
, function 获取像素(){ ,,,var pos=0; ,,,var 数据=https://www.yisu.com/zixun/imageData.data;//RGBA的一维数组数据//源图像的高度和宽度为300 px (var i=1;我<=image.width; + +) { (var j=1; <=image.height; j + +) { pos=[(张)* image.width + (j - 1) * 4;//取得像素位置 如果(数据(pos)>=0) {={var像素 x: (canvas.width-image.width)/2 + j + math . random() * 20,//重新设置每个像素的位置信息 y:我(canvas.height-image.height)/2 + + math . random() * 20,//重新设置每个像素的位置信息 fillStyle:“rgba(' +数据(pos) + ', ' +(数据(pos + 1)) + ', ' +(数据(pos + 2)) + ', ' +(数据(pos + 3)) + ') ' } pixels.push(像素); } } } } drawPixels函数(){ 画布var=. getelementbyid (“myCanvas”); var ctx=canvas.getContext (2 d); ctx.clearRect (0, 0, canvas.width canvas.height); var len=像素。长度,curr_pixel=零; (var=0;我<兰;我+ +){ curr_pixel=像素(我); ctx。fillStyle=curr_pixel.fillStyle; ctx.fillRect (curr_pixel。x, curr_pixel。y, 1,1); } }
<>强粒子时钟强>
渲染文字时钟
, function 时间(),{ ,,,ctx.clearRect (0, 0, canvas.width canvas.height) ,,,ctx.font =,“150 px 黑体“; ,,,ctx.textBaseline=& # 39;顶部# 39;; ,,,ctx.fillStyle =,“rgba (245245245, 0.2)“; ,,,ctx.fillText (new 日期().format (& # 39; hh: mm: ss # 39;), (canvas.width-textWidth)/2, (canvas.height-textHeight)/2, textWidth, textHeight); 以前,,}使用帆布怎么实现一个粒子动效