I have an SVG with an animation using requestAnimationFrame and the animation works but what I want it to do is animate over 3 secs and then repeat, so the animation for the circle will animate the dasharray and dashoffsset over 3seconds I don't know how to do this using css because it requires a calculation in javascript using Math.Pi can someone see if they can make this animation work the way I described. codepen.io
HTML
<svg width="20" height="20" viewBox="0 0 20 20">
<circle cx="10" cy="10" r="7" fill="none" stroke="#e6e6e6" stroke-width="6" />
<circle id="shape" cx="10" cy="10" r="7" fill="none" stroke="#ff0000" stroke-width="6" stroke-linecap="square" />
</svg>
CSS
#shape {
fill: none;
stroke: red;
stroke-width: 6;
transition: all 4s ease-in-out;
transform: rotate(-90deg);
transform-origin: 50%;
}
JavaScript
var endPercentage = 100;
var shape = document.getElementById('shape');
var circumference = Math.PI * parseFloat(shape.getAttribute('r')) * 2;
shape.setAttribute('stroke-dasharray', circumference);
shape.setAttribute('stroke-dashoffset', circumference);
var updatePercentage = function () {
var dashOffset = parseFloat(getComputedStyle(shape)['stroke-dashoffset']);
var curPercentage = Math.floor((100 * (circumference - dashOffset)) / circumference) || 0;
document.getElementById('perc').getElementsByClassName('value')[0].innerText = curPercentage;
if (curPercentage < endPercentage) {
window.requestAnimationFrame(updatePercentage);
}
}
var animateShape = function (percent) {
var offset = circumference - (circumference * percent / 100);
shape.setAttribute('stroke-dashoffset', offset);
window.requestAnimationFrame(updatePercentage);
}
setTimeout(function () {
animateShape(endPercentage);
}, 0);
You can define pi with:
:root {
--PI: 3.14159265358979;
}
...
stroke-dashoffset: calc(2 * var(--PI) * 7);
/* 7 is the radius of your circle */
With a combination of this and calc, you should be able to get a pure CSS solution.
If you still want to go via the JS route, I recommend:
shape.animate([
{ strokeDashoffset: 0 },
{ strokeDashoffset: circumference }
], { duration: 3000, iterations: Infinity });
Warning: polyfill required for older browsers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.