gpt4 book ai didi

javascript 呼吸元素 - 动画似乎在很长一段时间后才起作用

转载 作者:行者123 更新时间:2023-12-03 03:08:40 25 4
gpt4 key购买 nike

这是我作为练习的一部分为了好玩而编写的第一个代码片段。我创建了一个 300 × 300 像素的盒子,其中两个 Angular 的 border-radius 增大和减小,以创建呼吸动画。几分钟后,动画似乎加速并颤动。有人知道如何改进代码吗?

function frame() {
var elem = document.getElementById('box1');
var radius = 0;
var id1 = setInterval(frame1, 20);
var id2 = setInterval(frame2, 20);

function frame1() {
if (radius == 300) {
clearInterval(id1);
setInterval(frame2, 20);
} else {
clearInterval(id2);

radius ++;

elem.style.borderTopRightRadius = radius + 'px';
elem.style.borderBottomLeftRadius = radius + 'px';
}

return radius;
}

function frame2() {
if (radius == 0) {
clearInterval(id2);
setInterval(frame1, 20);
} else {
clearInterval(id1);

radius --;

elem.style.borderTopRightRadius = radius + 'px';
elem.style.borderBottomLeftRadius = radius + 'px';
}

return radius;
}
}

frame()

最佳答案

使用 requestAnimationFrame 并根据耗时和一些肮脏的数学计算动画

var elem = document.getElementById("box1");
var radius = 0;
var begin;
function frame(v) {
if(begin === undefined) {
begin = v;
}
let radius = Math.abs((300 + (v - begin) / 20) % 600 - 300);
elem.style.borderTopRightRadius = radius + "px";
elem.style.borderBottomLeftRadius = radius + "px";
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
#box1 {
width:500px;
height:500px;
background:dodgerblue;
}
<div id="box1">
</div>

But CSS animation is probably better for such a simple animation

#box1 {
width:500px;
height:500px;
background:dodgerblue;
}
#box1 {
animation:breath 6s infinite linear alternate;
}
@keyframes breath {
from { border-radius: 0 0 0 0; }
to { border-radius: 0 300px 0 300px; }
}
<div id="box1">
</div>

这是上面两种方法的并排

var elem = document.getElementById("box1");
var radius = 0;
var begin;
var maxRadius = 100;
var x = 60;
function frame(v) {
if(begin === undefined) {
begin = v;
}
let radius = Math.abs((maxRadius + (v - begin) / x) % (maxRadius *2) - maxRadius);
elem.style.borderTopRightRadius = radius + "px";
elem.style.borderBottomLeftRadius = radius + "px";
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
#box1 {
width:200px;
height:200px;
background:dodgerblue;
display:inline-block;
margin-right:20px;
}


#box2 {
width:200px;
height:200px;
background:dodgerblue;
display:inline-block;
}
#box2 {
animation:breath 6s infinite linear alternate;
}
@keyframes breath {
from { border-radius: 0 0 0 0; }
to { border-radius: 0 50% 0 50%; }
}
<div id="box1">
</div>
<div id="box2">
</div>

这两种方法都应该不受由于选项卡位于后台等原因造成的任何计时问题的影响

关于javascript 呼吸元素 - 动画似乎在很长一段时间后才起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47051680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com