圆形进度条的实现方法

这个进度条是用canvas进行绘制的


js 部分

<script>

window.onload = function(){
    //canvas initialization
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    //dimensions
    var W = canvas.width;
    var H = canvas.height;
    //Variables
    var degress = 0;
    var new_degrees = 0;
    var difference = 0;
    var color = "red"; //green looks better to me
    var bgcolor = "#892356";
    var text;
    var animation_loop, redraw_loop;
    var numBer=360  //定义百分比

    function init()
    {
        //Clear the canvas everytime a chart is drawn
        ctx.clearRect(50, 0, W, H);

        //Background 360 degree arc
        ctx.beginPath();
        ctx.strokeStyle = bgcolor;
        ctx.lineWidth = 10;    //预填充环的宽度
        ctx.arc(W/2, H/2, 60, 0, Math.PI*2, false); //you can see the arc now
        ctx.stroke();

        //gauge will be a simple arc
        //Angle in radians = angle in degrees * PI / 180
        var radians = degrees * Math.PI / 180;
        ctx.beginPath();
        ctx.strokeStyle = color;
        ctx.lineWidth = 10;    //填充环的宽度
        //The arc starts from the rightmost end. If we deduct 90 degrees from the angles
        //the arc will start from the topmost end
        ctx.arc(W/2, H/2, 60, 0 - 90*Math.PI/180, radians - 90*Math.PI/180, false);
        //you can see the arc now
        ctx.stroke();

        //Lets add the text

        ctx.font = "50px bebas";
        text = Math.floor(degress/360*100) + "%";
        //Lets center the text

        //deducting half of text width from position x
        text_width = ctx.measureText(text).width;
        //adding manual value to position y since the height of the text cannot
        //be measured easily. There are hacks but we will keep it manual for now.
        ctx.fillText(text, W/2 - text_width/2, H/2 + 15);
    }

    function draw()
    {
        //Cancel any movement animation if a new chart is requested
        if(typeof animation_loop != undefined) clearInterval(animation_loop);
        new_degrees=new_degrees+1;
        difference = new_degrees - degrees;
        animate_to();
    }

    //function to make the chart move to new degrees
    function animate_to()
    {
        //clear animation loop if degrees reaches to new_degrees
        if(degrees == new_degrees)
            clearInterval(animation_loop);

        if(degrees>=numBer)//如果加载到了360度,就停止
            return;

        if(degrees < new_degrees)
            degrees++;
        else
            degrees--;

        init();
    }

    //调用各个函数,实现动态效果
    draw();
    redraw_loop = setInterval(draw, 1); //Draw a new chart every 2 seconds

}

</script>

html部分

<canvas id="canvas"></canvas>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值