Skip to content

Instantly share code, notes, and snippets.

@VandeurenGlenn
Created May 15, 2021 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VandeurenGlenn/af98158837b13b1253758fcdda41b3ae to your computer and use it in GitHub Desktop.
Save VandeurenGlenn/af98158837b13b1253758fcdda41b3ae to your computer and use it in GitHub Desktop.
class ProgressRing extends HTMLElement {
constructor() {
super();
const stroke = this.getAttribute('stroke');
const radius = this.getAttribute('radius');
const normalizedRadius = radius - stroke * 2;
this._circumference = normalizedRadius * 2 * Math.PI;
this._root = this.attachShadow({mode: 'open'});
this._root.innerHTML = `
<svg
height="${radius * 2}"
width="${radius * 2}"
>
<circle
stroke="white"
stroke-dasharray="${this._circumference} ${this._circumference}"
style="stroke-dashoffset:${this._circumference}"
stroke-width="${stroke}"
fill="transparent"
r="${normalizedRadius}"
cx="${radius}"
cy="${radius}"
/>
</svg>
<style>
circle {
transition: stroke-dashoffset 0.35s;
transform: rotate(-90deg);
transform-origin: 50% 50%;
}
</style>
`;
}
setProgress(percent) {
const offset = this._circumference - (percent / 100 * this._circumference);
const circle = this._root.querySelector('circle');
circle.style.strokeDashoffset = offset;
}
static get observedAttributes() {
return ['progress'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'progress') {
this.setProgress(newValue);
}
}
}
window.customElements.define('progress-ring', ProgressRing);
// emulate progress attribute change
let progress = 0;
const el = document.querySelector('progress-ring');
const interval = setInterval(() => {
progress += 10;
el.setAttribute('progress', progress);
if (progress === 100)
clearInterval(interval);
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment