圆形进度条不是从中间开始的

时间:2018-02-13 12:51:52

标签: javascript html css

我有一个循环进度条,必须从0度开始 - 圆圈顶部的中间。但是我注意到它不是从中间开始,而是从左边开始。我该如何解决这个问题? 这是代码:



var bar = document.getElementById('progressbar'),
  createProgressBar = function(bar) {
    var options = {
        start: 0,
        width: bar.getAttribute('data-width'),
        height: bar.getAttribute('data-height'),
        percent: 90,
        lineWidth: bar.getAttribute('data-linewidth')
      },
      canvas = document.createElement('canvas'),
      paper = canvas.getContext('2d'),
      span = document.createElement('span'),
      radius = (options.width - options.lineWidth) / 2,
      color = paper.createLinearGradient(0, 0, options.width, 0),
      step = 1.5;

    span.style.width = bar.style.width = options.width + 'px';
    span.style.height = bar.style.height = options.height + 'px';
    canvas.width = options.width;
    canvas.height = options.height;
    span.style.lineHeight = options.height + 'px';

    color.addColorStop(0, "red");
    color.addColorStop(0.5, "red");
    color.addColorStop(1.0, "red");

    bar.appendChild(span);
    bar.appendChild(canvas);

    (function animat() {
      span.textContent = options.start + '%';
      createCircle(options, paper, radius, color, Math.PI * 1.5, Math.PI * step);
      console.log(step);
      options.start++;
      step += 0.02;
      if (options.start <= options.percent) {
        setTimeout(animat, 10);
      }
    })();
  },

  createCircle = function(options, paper, radius, color, start, end) {
    paper.clearRect(
      options.width / 2 - radius - options.lineWidth,
      options.height / 2 - radius - options.lineWidth,
      radius * 2 + (options.lineWidth * 2),
      radius * 2 + (options.lineWidth * 2)
    );

    paper.beginPath();
    paper.arc(options.width / 2, options.height / 2, radius, 0, Math.PI * 2, false);
    paper.strokeStyle = '#dbd7d2';
    paper.lineCap = 'round';
    paper.lineWidth = options.lineWidth;
    paper.stroke();
    paper.closePath();

    paper.beginPath();
    paper.arc(options.width / 2, options.height / 2, radius, start, end, false);
    paper.strokeStyle = color;
    paper.lineCap = 'square';
    paper.lineWidth = options.lineWidth;
    paper.stroke();
    paper.closePath();
  };

createProgressBar(bar);
&#13;
#progressbar {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -150px;
  margin-left: -150px;
}

canvas {
  position: absolute;
  display: block;
  left: 0;
  top: 0
}

span {
  display: block;
  color: #222;
  text-align: center;
  font-family: "sans serif", tahoma, Verdana, helvetica;
  font-size: 30px
}
&#13;
<div id="progressbar" data-width="320" data-height="320" data-linewidth="16"></div>
&#13;
&#13;
&#13;

进度条的样子:https://jsfiddle.net/ue20b8bd/

P.S。我已经从github修改了代码:https://github.com/su-ning/html5-circle-progressbar

1 个答案:

答案 0 :(得分:1)

问题在于lineCap属性。使用&#39; butt&#39;作为lineCap解决了问题!