如何在Chrome中优化图像序列?

时间:2014-08-11 21:02:50

标签: jquery css jquery-ui google-chrome background-size

在网站上,我有一个滑块(我使用jQuery UI' s滑块),用于控制图像序列。图像在页面背景中全屏显示(我使用background-size:cover)。在我的开发PC上,它运行得很好,但是当我在功能不太强大的计算机上试用它时,它会很滞后。

我执行序列的方式非常简单。这是我的一些代码,可以大致了解我正在做的事情。 (我认为代码对我的问题不是必不可少的,但无论如何我都加了......请随意跳过!)

HTML:

<div id="animation">
    <div class="frame frame0"></div>
    <div class="frame frame1"></div>
    <div class="frame frame2"></div>
    [...]
    <div class="frame frame20"></div>
</div>

CSS:

#animation {
    height: 100%;
    position: relative;
    width: 100%;
}
#animation div.frame {
    background-position: center center;
    background-size: cover;
    bottom: 0;
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 1;
}
#animation div.frame.active { z-index: 2; }
#animation div.frame0 { background-image: url(frame0.jpg); }
#animation div.frame1 { background-image: url(frame1.jpg); }
[...]
#animation div.frame20 { background-image: url(frame20.jpg); }

jQuery的:

var $frames = $('#animation').find('div.frame');
$('#slider').slider({
    value: 1,
    min: 1,
    max: 21,
    step: 1,
    slide: function(event, ui){
        $frames.removeClass('active').filter(':eq(' + (ui.value - 1) + ')').addClass('active');
    }
});

通过测试不同的东西,我设法找出了导致Chrome出现性能问题的原因。罪魁祸首是背景大小:封面。只要删除background-size属性并使用图像默认大小,我就会接近无滞后。

当我使用background-size:cover并且我的图片大小与我的Chrome窗口大小相同时,性能会更好。但是相对于原始图像尺寸拉伸(或压缩)图像越大,我得到的滞后越多。

到目前为止,我唯一能够优化它的方法是使用不同的图像大小并使用JavaScript以更接近浏览器窗口的大小加载序列,并希望它不会变得迟钝。这意味着如果用户调整浏览器窗口大小,我可能需要重新加载另一个图像工具包。

知道如何优化Chrome中的图像序列以获得更好的性能吗?

1 个答案:

答案 0 :(得分:0)

我今天使用画布而不是每个帧的HTML元素列表进行了测试。它在Chrome中产生了非常好的性能。画布解决方案的缺点是它不能在IE8中运行,但对于这个项目,我们在Chrome上的用户数量远远超过IE8,因此我可以接受它。

这帮我画了画布:Frame by frame animation in HTML5 with canvas

其余的只是修改滑块更改上的画布,而不是添加和删除活动类。

var arrFrames = [];
for(var i = 0; i < 21; i++){
    arrFrames[i] = new Image();
    arrFrames[i].onload = function() { /* check that all images are loaded before allowing the animation on the slider */ }
    arrFrames[i].src = 'frame' + i + '.jpg';
}

$('#slider').slider({
    value: 0,
    min: 0,
    max: 20,
    step: 1,
    slide: function(event, ui){
        /* Calculate image size and ratio */
        ctx.clearRect(0, 0, iCanvasWidth, iCanvasHeight);
        ctx.drawImage(arrFrames[ui.value], 0, 0, iWidth, iHeight);
    }
});

我没有在代码中放置所有变量定义以保持简洁和干净,但变量名称应该足够清楚,以了解它们具有什么价值。

我意识到的一件重要事情:不要忘记在javascript中设置画布的宽度和高度。仅在CSS中设置它只会拉伸它。

相关问题