canvas圓形進度條註釋超全

weixin_33890499發表於2017-12-28
 <!DOCTYPE html>
 <html>
<head>
<meta charset="UTF-8">
<title></title>

<style>
*{margin:0;padding:0;}
body{text-align:center;}
</style>

</head>
<body>

<canvas id="canvas" width="200" height="200" style="position:         absolute;left: 0px;background: #000;"></canvas>
<script>
    window.onload = function(){
        var canvas = document.getElementById('canvas'),  //獲取canvas    元素
            context = canvas.getContext('2d'),  //獲取畫圖環境,指明為2d
            centerX = canvas.width/2,   //Canvas中心點x軸座標
            centerY = canvas.height/2,  //Canvas中心點y軸座標
            rad = Math.PI*2/100, //將360度分成100份,那麼每一份就是rad度
            speed = 0.1; //載入的快慢就靠它了
     
         
    //繪製5畫素寬的運動外圈
    function blueCircle1(n){
        context.save();
        context.strokeStyle = "red"; //設定描邊樣式
        context.lineWidth = 5; //設定線寬
        context.beginPath(); //路徑開始
        context.arc(centerX, centerY, 50 , -Math.PI/2, -Math.PI/2 +n*rad, false); //用於繪製圓弧context.arc(x座標,y座標,半徑,起始角度,終止角度,順時針/逆時針)
        context.stroke(); //繪製
        context.closePath(); //路徑結束
        context.restore();
    }

    //繪製白色外圈
    function whiteCircle1(){
        context.save();
        context.beginPath();
        context.lineWidth = 5; //設定線寬
        context.strokeStyle = "#444444";
        context.arc(centerX, centerY, 50 , 0, Math.PI*2, false);
        context.stroke();
        context.closePath();
        context.restore();
    } 

    //百分比文字繪製
    function text(n){
        context.save(); //save和restore可以保證樣式屬性只運用於該段canvas元素
        context.strokeStyle = "#fff"; //設定描邊樣式
        context.font = "20px Arial"; //設定字型大小和字型
        //繪製字型,並且指定位置
        context.strokeText(n.toFixed(0)+"%", centerX-15, centerY+10);//字的位置
        context.stroke(); //執行繪製
        context.restore();
    }
    //動畫迴圈
    (function drawFrame(){
        window.requestAnimationFrame(drawFrame);
        context.clearRect(0, 0, canvas.width, canvas.height);
        whiteCircle1();
      
        text(speed);
        blueCircle1(speed);
       
        if(speed > 100) speed = 0;
        speed += 0.1;
       
    }());
}
</script>

</body>
</html>

相關文章