CSS随机动画

6

我的想法是将一张图片分解成小部分,然后它们会随着缩小而飞散开。

我已经用几个CSS动画实现了这一点——scale + translate3d——(结果不是很好,但至少是个开端)。

现在,问题是我希望翻译是随机的。据我所知,有一种简单的方法涉及JS/Jquery/GSAP,还有一种稍微复杂一些的方法涉及SCSS/Sass…

我对它们都不熟悉。

我找到了一段代码,用javascript来随机旋转,并将其改变为我的翻译方式。

该代码的发帖位置在这里

// search the CSSOM for a specific -webkit-keyframe rule
function findKeyframesRule(rule)
{
    // gather all stylesheets into an array
    var ss = document.styleSheets;

    // loop through the stylesheets
    for (var i = 0; i < ss.length; ++i) {

        // loop through all the rules
        for (var j = 0; j < ss[i].cssRules.length; ++j) {

            // find the -webkit-keyframe rule whose name matches our passed       over parameter and return that rule
            if (ss[i].cssRules[j].type == window.CSSRule.WEBKIT_KEYFRAMES_RULE && ss[i].cssRules[j].name == rule)
                return ss[i].cssRules[j];
        }
    }

    // rule not found
    return null;
}

// remove old keyframes and add new ones
function change(anim)
{
    // find our -webkit-keyframe rule
    var keyframes = findKeyframesRule(anim);
    // remove the existing 38% and 39% rules
    keyframes.deleteRule("38%");
    keyframes.deleteRule("39%");
    // create new 38% and 39% rules with random numbers
    keyframes.insertRule("38% { -webkit-transform: translate3d("+randomFromTo(-100,100)+"vw,"+randomFromTo(-100,100)+"vw,0vw); }");
    keyframes.insertRule("39% { -webkit-transform: translate3d("+randomFromTo(-100,100)+"vw,"+randomFromTo(-100,100)+"vw,0vw); }");
    // assign the animation to our element (which will cause the animation to run)
    document.getElementById('onet').style.webkitAnimationName = anim;
}

// begin the new animation process
function startChange()
{
    // remove the old animation from our object
    document.getElementById('onet').style.webkitAnimationName = "none";
    // call the change method, which will update the keyframe animation
    setTimeout(function(){change("translate3d");}, 0);
}

// get a random number integer between two low/high extremes
function randomFromTo(from, to){
   return Math.floor(Math.random() * (to - from + 1) + from);
}

所以最后,有这一部分:
$(function() {
    $('#update-box').bind('click',function(e) {
        e.preventDefault();
        startChange();        
    });
});

我不确定,但我猜它的功能是触发 startChange 函数。

现在,在我的情况下,我想让一个函数自动触发,并且由于动画必须继续播放,它必须无限循环。

有什么想法吗?我猜我可以使用 onAnimationEnd.. 但显然我不知道如何编写它...


我的回答应该能够解决你的问题。如果你需要其他方面的解释,我会在我的回答中添加。 - Dodo
1个回答

3
内置的JavaScript函数setTimeout(functionName, time)会在time毫秒后调用名为functionName的函数。删除$('#update-box').bind...部分,替换为每1000ms左右调用一次的函数。例如:
$(function() {
    function callStartChange() {
        startChange();
        setTimeout(callStartChange, 1000);
    }
    // And now start the process:
    setTimeout(callStartChange, 1000);
});

每秒钟(1000ms)将调用startChange函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接