Html5 loading 动画效果

作者: jaclon 分类: JS 发布时间: 2013-11-08 13:16 ė 6没有评论

按照惯例,直接上代码

function loading(canvas, options) {
    this.canvas = canvas;
    if (options) {
        this.radius = options.radius || 12;
        this.circleLineWidth = options.circleLineWidth || 4;
        this.circleColor = options.circleColor || 'lightgray';
        this.moveArcColor = options.moveArcColor || 'gray';
    } else {
        this.radius = 12;
        this.circelLineWidth = 4;
        this.circleColor = 'lightgray';
        this.moveArcColor = 'gray';
    }
}
loading.prototype = {
    show : function () {
        var canvas = this.canvas;
        if (!canvas.getContext)
            return;
        if (canvas.__loading)
            return;
        canvas.__loading = this;
        var ctx = canvas.getContext('2d');
        var radius = this.radius;
        var me = this;
        var rotatorAngle = Math.PI * 1.5;
        var step = Math.PI / 6;
        canvas.loadingInterval = setInterval(function () {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                var lineWidth = me.circleLineWidth;
                var center = {
                    x : canvas.width / 2,
                    y : canvas.height / 2
                };
                ctx.beginPath();
                ctx.lineWidth = lineWidth;
                ctx.strokeStyle = me.circleColor;
                //事圆弧
                ctx.arc(center.x, center.y, radius, 0, Math.PI * 2);
                ctx.closePath();
                ctx.stroke();//填充
                //在圆圈上面画小圆
                ctx.beginPath();
                ctx.strokeStyle = me.moveArcColor;
                ctx.arc(center.x, center.y, radius, rotatorAngle,
rotatorAngle + Math.PI * .45);
                ctx.stroke();
                rotatorAngle += step;

            }, 50);
    },
    hide : function () {
        var canvas = this.canvas;
        canvas.__loading = false;
        if (canvas.loadingInterval) {
            window.clearInterval(canvas.loadingInterval);
        }
        var ctx = canvas.getContext('2d');
        if (ctx)
            ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
};
var loadingObj = new loading(document.getElementById('canvas'),
{radius:8,circleLineWidth:3});
loadingObj.show();

效果图:

loading 效果

loading 效果

再来看看上面的代码:
context.arc(x, y, radius, startAngle, endAngle, anticlockwise)
arc是画圆弧方法,x,y圆心坐标,radius为半径,startAngle、endAngle分别为起始角度和结束角度,anticlockwise为画图方向,逆时针(true)

上面的实例中
ctx.arc(center.x, center.y, radius, rotatorAngle, rotatorAngle + Math.PI * .45);意思为以center.x center.y为中心坐标,以radius为半径,以ratatorAngle为起始角度,rotatorAngle + Math.PI * .45为结束角度,顺时针画图。

其中rotatorAngle = Math.PI * 1.5;我刚开始也不理解,数学还给老师了。。
我们先看一张图

PI

PI

这张图中标出了Math.PI,即∏与角度的关系。∏可以理解为180度角

本文出自 肥蕉博客@IT技术,热门话题,生活随笔,美图欣赏,转载时请注明出处及相应链接。

本文永久链接: http://www.bananawolf.com/html/2013/11/961.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*

Ɣ回顶部