canvas弧形進度條

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <style>
    #circle{
      outline: 1px solid black;
      /* 使用大尺寸再縮小,可以緩解屏幕渲染精度低,邊緣毛糙的現象 */
      transform: scale(0.2);
    }
  </style>
</head>

<body>
  <canvas id="circle" height="1000px" width="1000px">
  </canvas>
</body>
<script src="./zxk.js">
</script>

</html>
/**
 * @description 畫圓弧進度條
 * @date 2019-11-20
 * @param {Number} percentage 比例,0-1之間
 */
function circle(percentage) {
  const canvas = document.querySelector('#circle');;
  const ctx = canvas.getContext('2d');

  /* 畫筆圓公共的配置 */
  const commmonObj = {
    /* 2d上下文 */
    ctx: ctx,
    /*圓心*/
    x: 500,
    y: 500,
    /*半徑*/
    radius: 400,
    /*環的寬度*/
    lineWidth: 50
  };
  /* 點亮的區域 */
  const activeObj = {
    ...commmonObj,
    /* 開始畫的角度,從120°的地方起筆 */
    startAngle: (Math.PI * 2 * 120) / 360,
    /* 結束的角度,根據傳入的比例計算結束的角度,整個進度條的角度是(360-60)° */
    endAngle: (Math.PI * 2 * (120 + (360 - 60) * percentage)) / 360,
    /* 顏色 */
    color: '#28BF68'
  };
  /* 灰色區域 */
  const backObj = {
    ...commmonObj,
    /* 灰色開始的角度就是點亮區域結束的角度 */
    startAngle: activeObj.endAngle,
    /* 結束的角度,從120°的地方開始,到60°的地方結束 */
    endAngle: (Math.PI * 2 * 60) / 360,
    /* 顏色 */
    color: '#ecf9ef'
  };
  drawCircle(backObj);
  drawCircle(activeObj);
}
/**
 * @description 畫曲線
 * @date 2019-11-20
 * @param {Object} circleObj 畫線配置
 */
function drawCircle(circleObj) {
  const ctx = circleObj.ctx;
  ctx.beginPath();
  ctx.arc(
    circleObj.x,
    circleObj.y,
    circleObj.radius,
    circleObj.startAngle,
    circleObj.endAngle,
    false
  );
  //設定曲線粗細度
  ctx.lineWidth = circleObj.lineWidth;
  //給曲線着色
  ctx.strokeStyle = circleObj.color;
  //連接處樣式
  ctx.lineCap = 'round';
  //給環着色
  ctx.stroke();
  ctx.closePath();
}


let n = 1;
const tiktok = setInterval(() => {
  n++
  if(n/500>=1) {
    circle(1);
    clearInterval(tiktok)
  } else {
    circle(n / 500);
  }
}, 10);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章