1

I am trying to style a circle showing the progress percent as the circumference. I want to get the radius in JS but style the circle in CSS. The function I use to do this is setPercent. It reads the radius of the circle by selecting the radius element and getting the radius measures from there.

This is the code that works:

const fn = function() {
  let circle = document.querySelector('circle.percent')
  debugger
  let radius = circle.r.baseVal.value
  let circumference = 2 * Math.PI * radius
  circle.style.strokeDasharray = `${circumference} ${circumference}`


  this.setPercent = function(percent) {
    circle.style.strokeDashoffset = (100 - percent) / 100 * circumference
  }
}
setTimeout(fn, 1)
:root {
  --back-ground: #30384a;
  --neutral-circle-border: #656c79;
  --completed-color: #67ed8b;
  background: var(--back-ground)
}

div.normal_square {
  width: 100px;
  height: 100px;
}

svg.progress-ring {
  margin: 0 auto;
  display: block;
}

svg.progress-ring circle {
  fill: transparent;
  stroke-width: 2;
  stroke: black;
  cx: 50%;
  cy: 50%;
  r: 40%;
}

svg.progress-ring circle.percent {
  transition: all 0.5s ease-out;
  transform: rotate(-90deg);
  transform-origin: 50% 50%;
}

svg.progress-ring circle.background {
  stroke: var(--neutral-circle-border)
}
<div margin="0 auto">
  <svg class="progress-ring" width="200px" height="200px" xmlns="http://www.w3.org/2000/svg">
      <circle class="background"/>
      <circle class="percent" fill="transparent" stroke-width="6" stroke="black" cx="50%" cy="50%" r="40%" />
    </svg>
</div>

However, when I remove that r="40%" from my code, I can't get the radius measured from circle.r.... Why does it happen and how can I fix it?

Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
shampoo
  • 1,173
  • 12
  • 22
  • For now you can't change the circle's radius in CSS. Please take a look at this: https://stackoverflow.com/questions/14255631/style-svg-circle-with-css – enxaneta Aug 12 '19 at 07:18

2 Answers2

0

Use window.getComputedStyle(element) to retrieve the value instead.

Currently you're retrieving the property value from the element reference, when you remove the property there's nothing left to retrieve.

Etheryte
  • 24,589
  • 11
  • 71
  • 116
  • Thanks, I tried that too but the problem is that returns "40%" not the actual pixels, unlike the other method. I don't understand why this happens, because the circle still exists and it has a radius, it makes sense to be able to get that through element properties. – shampoo Aug 12 '19 at 16:24
0

Just ran into the same problem. This worked:

let radius = circle.getBoundingClientRect().width / 2;

Seems silly to have to do this though. Hopefully someone posts a better way.

Julian TF
  • 465
  • 5
  • 10