2

我有一个关于使用 DOM 在 HTML 中通过 javascript 动画的问题。在这种情况下,我使用绝对位置和 css + jQuery 并为 div 设置动画。

因此,当我遍历我的大量位置 x,y 时,动画运行速度非常慢。我以 100 毫秒(80 毫秒)的间隔运行,但渲染速度似乎不够快,我的动画需要超过 10 秒...

重新运行动画时,似乎指令已被某种方式缓存(渲染)并且我的动画运行得非常完美。

然后,如果我再等 5 分钟,它会再次变慢。(好像是低级机器码内存已经被删除了,因为没有再用了?)

我只是不知道如何让我的动画顺利运行,如果它是第一次执行的话。我尝试使用 fabric.js 来渲染动画......同样的问题。在第一次运行它很慢。第二轮和后续都很顺利。

function render_mouse()
 {
     if(play_pos < mousefile_length)
         {
            $('.mouse').remove();
            $("body").append(
            $('<div id="mouse" class="mouse"></div>')
            .css('position', 'absolute')
            .css('top', play_mousefile[play_pos+1] + 'px')
            .css('left', play_mousefile[play_pos] + 'px')
            .css('width', mousesize)
            .css('height', mousesize)
            .css('background-image', 'url(images/cursor.png')
                    );
            play_pos = play_pos +2;
            }
    else {
        clearInterval(play_mousetimer);
         }
   }

UPDATED:
 $('#mouse').animate({
                 left: rec_mousefile[play_pos]+"px",
                 top : rec_mousefile[play_pos+1]+"px"
                 },80);
4

1 回答 1

2

如果你没有每次都对鼠标 div 做这么多的操作,动画会更快。

基本上,将鼠标附加到 dom 一次,使用初始渲染所需的所有 CSS,缓存对附加元素的引用,然后仅操作动画所需的 css 属性。

通过将元素保留在 dom 中,而不是每次都删除并重新添加,您应该会看到一些性能提升。此外,保存对附加元素的引用将防止您在进行另一个更新之前必须重新查询 dom。

由于缓存,动画在第二次运行时应该总是快一点,但这些优化应该至少有助于初始运行。

**根据评论进行编辑**

您可以在函数外部缓存对鼠标 div 的引用,或者将其挂在渲染函数本身之外,例如:

var mouseDiv = $('#mouse');

function render_mouse()
{
    if(mousefile_length > play_pos)
                {
                 mouseDiv.animate({
                 left: rec_mousefile[play_pos]+"px",
                 top : rec_mousefile[play_pos+1]+"px"
                 },80);

                 play_pos=play_pos+2;
        }
   else {playtimer.stop();}
}

或者

function render_mouse()
{
    // query the first time, and then use the cached version thereafter
    render_mouse.mouse = render_mouse.mouse || $('#mouse');
    if(mousefile_length > play_pos)
                {
                 render_mouse.mouse.animate({
                 left: rec_mousefile[play_pos]+"px",
                 top : rec_mousefile[play_pos+1]+"px"
                 },80);

                 play_pos=play_pos+2;
        }
   else {playtimer.stop();}
}
于 2012-06-26T17:59:07.640 回答