body {
background: #000;
text-align: center;
}
svg {
margin-top: 100px;
background: #fff;
}
path {
fill: none;
stroke-width: 6;
}
var cx = 400,
cy = 300,
r = 150,
oSvg = document.getElementById('svg');
// 里面的环
ring(-150,150,'#ccc');
function ring(startAng,endAng,stroke) {
var x1 = cx + Math.sin(d2r(startAng)) * r
var x2 = cx + Math.sin(d2r(endAng)) * r
var y1 = cy - Math.cos(d2r(startAng)) * r
var y2 = cy - Math.cos(d2r(endAng)) * r
var oPath = document.createElementNS('http://www.w3.org/2000/svg','path');
oPath.setAttribute('d',`
M${x1},${y1}
A${r} ${r} 0 ${Math.abs(endAng - startAng) >=180 ? 1 : 0} 1 ${x2} ${y2}
`);
oPath.style.stroke = stroke;
oSvg.appendChild(oPath);
}
function d2r(deg) {
return deg * Math.PI / 180;
}
// 两个环 = 里面的 + 外面的 其实只要两个path即可
// 里面的的画死的 外面的显示进度 本质就是结束角度在增加即可
// 先把里外的环都画出来 然后动态的改变的外环的结束的角度 就无需频繁的创建那么多path
ring(-150,-150,'red');
var oText = oSvg.querySelector('text');
var outer = oSvg.querySelector('path:nth-of-type(2)');
var startAng = -150,
currentAng = startAng,
endAng = 150;
var timer = setInterval(function() {
currentAng++;
// 计算度数
oText.innerHTML = Math.round((currentAng - startAng)/300 * 100 * 100)/100 + '%';
if(currentAng >= endAng) {
clearInterval(timer);
currentAng = endAng;
}
var x1 = cx + Math.sin(d2r(startAng)) * r;
var y1 = cy - Math.cos(d2r(startAng)) * r;
var x2 = cx + Math.sin(d2r(currentAng)) * r;
var y2 = cy - Math.cos(d2r(currentAng)) * r;
outer.setAttribute('d',`
M${x1},${y1}
A${r} ${r} 0 ${Math.abs(currentAng - startAng) >=180 ? 1 : 0} 1 ${x2} ${y2}
`);
outer.style.stroke = 'red';
//
},91);