[英]Javascript: code with no animation with requestAnimationFrame?
[英]3 sec animation that repeats with requestAnimationFrame
我有一个使用requestAnimationFrame动画的SVG并且动画可以工作,但我想要它做的是动画超过3秒然后重复,所以圆圈的动画将动画dasharray和dashoffsset超过3秒我不知道如何使用css执行此操作,因为它需要使用Math.Pi在javascript中进行计算,有人可以看到他们是否可以按照我描述的方式使用此动画。 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);
你可以用以下方法定义pi :
:root {
--PI: 3.14159265358979;
}
...
stroke-dashoffset: calc(2 * var(--PI) * 7);
/* 7 is the radius of your circle */
结合使用this和calc,您应该能够获得纯CSS解决方案。
如果您仍想通过JS路线,我建议:
shape.animate([
{ strokeDashoffset: 0 },
{ strokeDashoffset: circumference }
], { duration: 3000, iterations: Infinity });
警告:旧版浏览器需要填充多页填充。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.