在小间隔内通过javascript更新css时,会出现断断续续的动态观察动画

Stuttering orbit animation when updating css through javascript over small interval

本文关键字:断断续续 动画 观察 动态 css 更新 javascript      更新时间:2023-09-26

我正试图让一些DOM元素围绕一个固定点平滑旋转。我是用jQuery从头开始写这篇文章的,无论我为setInterval选择什么更新速度,或者我在每个循环中轨道前进的度数有多小,我都会得到这种刺耳的楼梯动画效果。我试过用jquery的.animate代替.css,希望它能让事情顺利进行,但我似乎无法让它发挥作用。感谢您的帮助。

换句话说,它不像在HTML5画布中旋转图像那样平滑。我想让它更光滑。

这里有一个jsFiddle演示这个问题。

注意到动画不太平滑吗?

供参考,这里是代码:

HTML

<div id="div"></div>
<div class="dot"></div>
<button class="stop">STOP</button>
<button class="start">START</button>

CSS

#div{
    position:absolute;
    height: 20px;
    width: 20px;
    background-color: #000;
}
.dot{
    position:absolute;
    width: 5px;
    height: 5px;
    background-color: #000;
}
button{
    position:absolute;
}
.stop{
    top:200px;
}
.start{
    top:225px;
}

所有重要的Java脚本

$(document).ready(function(){
    $('#div').data('angle', 90);
    var interval;
    $('.stop').on('click', function(){
        if(interval){
            clearInterval(interval);
            interval = undefined;
        }
    });
    $('.start').on('click', function(){
        if(!interval){
            interval = setBoxInterval();
        }
    });
    interval = setBoxInterval();
});
function drawOrbitingBox(degrees){
    var centerX = 100,
        centerY = 100,
        div = $('#div'),
        orbitRadius = 50;
    //dot might not be perfectly centered
    $('.dot').css({left:centerX, top:centerY});
    //given degrees (in degrees, not radians), return the next x and y coords
    function coords(degrees){
        return {left:centerX + (orbitRadius * Math.cos((degrees*Math.PI)/180)), 
                top :centerY - (orbitRadius * Math.sin((degrees*Math.PI)/180))};
    }
    //increment the angle of the object and return new coords through coords()
    function addDegrees(jqObj, degreeIncrement){
        var newAngle = jqObj.data('angle') + degreeIncrement;
        jqObj.data('angle', newAngle);
        return coords(newAngle);
    }
    //change the left and top css property to simulate movement
    //  I've tried changing this to .animate() and using the difference
    //  between current and last position to no avail
    div.css(addDegrees(div, degrees), 1);
}
function setBoxInterval(){
    var interval = window.setInterval(function(){
        drawOrbitingBox(-0.2); //This is the degree increment
    }, 10); //This is the amount of time it takes to increment position by the degree increment
    return interval;
}

我宁愿不使用外部库/插件,但如果这是公认的做这类事情的方式,我会的。谢谢你抽出时间。

这是因为您为顶部左侧属性设置的值是四舍五入的。您应该尝试使用CSS转换。结合CSS动画/转换和CSS转换,您也应该能够在没有JavaScript的情况下获得动画。

哦,我自己也碰到过!实际上你无能为力,你看到的口吃是像素大小。像素是基于css的动画的最小步骤,不能做"半像素"或"0.2像素"。您将看到css3动画中也会出现同样的情况。

恐怕唯一的解决办法就是加快你的动画制作速度。

此外,cosndsider使用rquestAnimationFrame而不是interval:https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame