requestAnimationFrame似乎很慢,cancelAnimationFrame无效

时间:2013-07-05 21:45:57

标签: javascript canvas

This is what I'm working on.如果您滚动到JS第63行,您将看到我遇到困难的功能。我试图用requestAnimationFrame替换我的setInterval代码(在注释中)。但动画似乎进展得相当缓慢,而且,它永远不会停止! Here is a working version with setInterval

相关JS:

function setGauge(val){
    var time = 350;
    time = time / (Math.abs(val - preVal));

    if (val > preVal) {
        function getHigher(){
           if (preVal == val)
                cancelAnimationFrame(animate);
            preVal++;
            drawValueArc(preVal);
            var animate = requestAnimationFrame(getHigher);
        }
        getHigher();
        /*
        var animate = setInterval(function(){
            if (preVal == val)
                clearInterval(animate);
            preVal++;
            drawValueArc(preVal);  
        }, time);
        */
    } else if (val < preVal) {
        function getLower(){
           if (preVal == val)
                cancelAnimationFrame(animate2);
            preVal--;
            drawValueArc(preVal);  
            var animate2 = requestAnimationFrame(getLower);
        }
        getLower();
        /*
        var animate2 = setInterval(function(){
            if (preVal == val)
                clearInterval(animate2);
            preVal--;
            drawValueArc(preVal);  
        }, time);
        */
    } 
}

1 个答案:

答案 0 :(得分:3)

我稍微修改了代码,你几乎就在那里。

我们并不真正需要animateanimate2,因为我们不取消requestAnimationFrame(rAF),而只是检查它的运行条件是否存在:

function setGauge(val) {
    var time = 350;
    time = time / (Math.abs(val - preVal));

    if (val > preVal) {
        function getHigher() {
            preVal++;
            drawValueArc(preVal);

            //if still less then rAF again
            if (preVal < val) requestAnimationFrame(getHigher);
        }
        getHigher();

    } else if (val < preVal) {
        function getLower() {
            preVal--;
            drawValueArc(preVal);

            //if still more then rAF again
            if (preVal > val) requestAnimationFrame(getLower);
        }
        getLower();

     //...
}

请参阅修改过的小提琴(链接似乎:

<击> http://jsfiddle.net/AbdiasSoftware/cUSBQ/11/