CSS3圖片幀動畫性能優化

有的複雜動畫效果咱們沒辦法用CSS3直接完成,設計師會給出圖片序列幀,咱們合成雪碧圖,經過steps改變background-position的方式來實現動畫,如Demo: https://ningwenjing.github.io...
代碼以下:css

.ico-vip{width: 44px;height: 30px;overflow: hidden;position: relative;background: url(spr-vip.png) no-repeat;animation: aniVip 1.5s steps(34) infinite;}
@keyframes aniVip {
    0%{background-position: 0 0;}  
    100%{background-position: -1564px 0}
}

可是使用這種寫法會致使配置比較差的電腦CPU消耗比較明顯。在Chrome按shift+esc查看任務管理器,能夠看到CPU的佔用會變化,這個值的最高點仍是比較高的。
cpu
background-position不斷的改變會形成瀏覽器不斷重繪而致使CPU上升,能夠點開Chrome開發者工具中的Layers看到,繪製一直在不斷地改變:
layerhtml

在網上查了一下,有同窗建議不要用background-position,能夠用translate來代替。因而嘗試了一下:https://ningwenjing.github.io...
代碼以下:git

.ico-vip{width: 44px;height: 30px;overflow: hidden;}
.ico-vip:after{content:''; width: 1564px;height: 30px;background: url(spr-vip.png) no-repeat;animation: aniVip 1.5s steps(34) infinite;display: block;}
@keyframes aniVip {
    0%{transform: translate3d(0,0,0)}  
    100%{transform: translate3d(-1564px,0,0)}
}

這種寫法不會致使重繪,能夠減小CPU的消耗。github

cpu

測試在比較差的機器上測試,CPU能夠從20%減小到4%,這個方法仍是比較可用的。瀏覽器

相關文章
相關標籤/搜索