Круглый прогресс бар с процентом сверху текущего положения бара
Решил сделать круглый прогресс бар, сверху текущего положения бара должен находиться текущий процент. Вот пример (Цвет текста на ваше усмотрение, я сделал его чёрным, чтобы его было лучше видно):
Взял основание у своего прошлого ответа (Второе решение). Вот то, что я смог придумать:
class CircleProgress {
constructor(progress, circleSize = 100) {
this.progress = progress
this.circleSize = circleSize
}
init(parentNode) {
let progress = this.progress
let circleSize = this.circleSize
let parentElement = parentNode || document.body
let progressNode = document.createElement('div')
let percentageNode = document.createElement('div')
progressNode.className = 'progress-circle'
progressNode.style.cssText = `
--progress: ${progress}%;
--circle-size: ${circleSize}px;`
let angle = progress * 360 / 100
let radius = circleSize / 2
let rad = angle * Math.PI / 180
let left = radius + radius * Math.sin(rad)
let top = radius + radius * Math.cos(rad)
percentageNode.className = 'progress-circle-percentage'
percentageNode.textContent = progress + '%'
percentageNode.style.cssText = `
left: ${left.toFixed(2)}px;
top: ${top.toFixed(2)}px;
transform: rotate(${angle}deg);`
progressNode.appendChild(percentageNode)
parentElement.appendChild(progressNode)
}
}
new CircleProgress(25)
.init()
new CircleProgress(50)
.init()
new CircleProgress(75, 150)
.init()
new CircleProgress(42, 150)
.init()
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.progress-circle {
--circle-size: 100px;
width: var(--circle-size);
height: var(--circle-size);
border-radius: 50%;
margin: 1.5em;
background-image: conic-gradient(rgb(100, 150, 220) var(--progress), rgb(240, 240, 240) 0);
position: relative;
}
.progress-circle::before {
--border-width: 10px;
--inner-circle-size: calc(var(--circle-size) - var(--border-width));
--inner-circle-gap: calc(var(--border-width) / 2);
content: '';
display: block;
width: var(--inner-circle-size);
height: var(--inner-circle-size);
background-color: rgb(255, 255, 255);
border-radius: 50%;
position: relative;
left: var(--inner-circle-gap);
top: var(--inner-circle-gap);
}
.progress-circle-percentage {
position: absolute;
font-family: 'Montserrat', 'Segoe UI';
color: rgb(80, 120, 170);
}
Как мы можем наблюдать, в первом кейсе всё работает как планировалось. Дальше я добавил ещё 3 круга и по какой-то причине, что-то пошло нет так, в чём может быть проблема? Я предполагаю, что я что-то не так написал в переменных left
и top
, возможно и радиан хранящийся в переменной (Переменная rad
) тоже не правильный, честно говоря, не уверен.