超酷!!HTML5 Canvas 水流样式 Loading 动画

今天我们要分享另一个基于 HTML5 的流式加载动画。此动画在加载时会呈现出液体流动的动画效果,并且由于与背景颜色的对比,还会呈现出轻微发光的动画效果。

效果预览

图片[1]-超酷!!HTML5 Canvas 水流样式 Loading 动画-唐朝资源网

代码实现

HTML 代码

接下来我们讲讲实现这个加载动画的大致思路和实现过程。

首先在页面上定义一个元素来承载此动画的画布。


您需要为下拉菜单定义一个 SVG 过滤器。该滤镜用于渲染圆形粒子效果。


CSS 代码

这里不说页面中其他元素的样式,我们的重点是为元素指定对应的svg:

#canvas {
	margin: 0px auto;
	display: block;
	filter: url("#shadowed-goo");
}

代码

然后使用代码实现加载动画。此处使用的 2d 动画绘制对象:

图片[2]-超酷!!HTML5 Canvas 水流样式 Loading 动画-唐朝资源网

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

() 方法返回一个对象,该对象提供在画布上绘图的方法和属性。

这个动画的核心是动态绘制圆弧,代码如下:

ctx.fillStyle = "rgba(255,255,255," + this.al + ")";
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
ctx.fill();

以下是完整的JS代码:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var p = [];
var particle = [];
var angle = Math.PI/4;
canvas.width = 600;
canvas.height = 600;
var width = canvas.width;
var height = canvas.height;
function getRandomInt(min, max) {

图片[3]-超酷!!HTML5 Canvas 水流样式 Loading 动画-唐朝资源网

return min + Math.floor(Math.random() * (max - min + 1)); } function retinaReady() { var pixelRatio = window.devicePixelRatio || 1; var backingStore = ctx.webkitBackingStorePixelRatio || 1; window.ratio = pixelRatio / backingStore; // public var if (pixelRatio !== backingStore) { var oldWidth = canvas.width; var oldHeight = canvas.height; canvas.width = oldWidth * ratio; canvas.height = oldHeight * ratio; canvas.style.width = oldWidth + "px"; canvas.style.height = oldHeight + "px"; ctx.scale(window.ratio, window.ratio); } } retinaReady(); function run(a) { var r = 140; var x = r * Math.sin(a) + width / 2; var y = r * Math.cos(a) + ((height / 2)-80);

图片[4]-超酷!!HTML5 Canvas 水流样式 Loading 动画-唐朝资源网

var p; p = new Particle(x, y); particle.push(p); } function Particle(x, y) { this.x = x; this.y = y; this.r = getRandomInt(10, 16); this.v = { x: 0, y: 0 }; this.a = { x: 0, y: 0 }; this.al = 1; } Particle.prototype.update = function() { this.a.x = getRandomInt(-0.001, 0.001);

图片[5]-超酷!!HTML5 Canvas 水流样式 Loading 动画-唐朝资源网

this.a.y = getRandomInt(0.01, 0.02); this.v.x += this.a.x; this.v.y += this.a.y; this.x += this.v.x; this.y += this.v.y; if (this.r >= 0.01) { this.r -= 0.2; this.al -= 0.001; } else { this.r = 0; this.al = 0; } }; Particle.prototype.draw = function() { ctx.fillStyle = "rgba(255,255,255," + this.al + ")"; ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false); ctx.fill(); };

图片[6]-超酷!!HTML5 Canvas 水流样式 Loading 动画-唐朝资源网

function animate() { ctx.clearRect(0, 0, width, height); run(angle); requestAnimationFrame(animate); for (var j = 0; j < particle.length; j++) { var p = particle[j]; p.update(); p.draw(); } if (angle <= 2 * Math.PI) { angle += 0.04; } else { angle = 0; } } animate();

至此,这个粒子流体加载动画就完成了,文章最后也会把源码献给大家。

源码下载

我已经编译了一个完整的源代码包,供大家下载学习。

© 版权声明
THE END
喜欢就支持一下吧
点赞10赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容