2015-02-11 24 views
1

幾天前我在Google Chrome中遇到問題。我喜歡像素藝術,我試圖用html5創建一個巨大的動畫地圖。當多個畫布同時運行時Chrome使用高cpu

一切都很好,直到我開始在同一時間使用超過5或6個畫布。 在Firefox和Internet Explorer中,地圖沒有問題,但在Chrome中,CPU達到70%,有時甚至更高。

你能給我提供一些關於如何在Chrome中解決這類問題的好建議嗎? 我一直在互聯網上搜索有關提高Chrome瀏覽器的性能,但沒有任何幫助。

感謝您的幫助。

僅供參考,這是地圖: http://pixelslivewallpaper.github.io/jadsdsengine/Zelda.htm

+0

似乎是很長的Firefox加載這裏 – nicolallias 2015-02-11 13:26:47

+0

這是正常的,也有大量的圖片加載的。 – Peppermint 2015-02-11 15:57:57

+0

事實上,你應該警告我們,你的問題中有~10分鐘的負荷。結果非常棒!不幸的是,不知道Chrome的狂熱 – nicolallias 2015-02-11 16:31:17

回答

3

解決方案:

最簡單的方式來解決這個問題是停止對用戶可見區域以外的所有畫布的動畫和後恢復它們。計算這個區域的方法是捕獲滾動位置。

顯然,Firefox和Internet Explorer自動執行此項工作,但在Google Chrome中,您需要手動執行此操作。

下面是代碼:

this.loadIsVisibleOptions = function() { 
    if (this.stopAnimationWhenIsNotVisible) { 
     window.addEventListener("scroll", function (event) { currentJadsdsEngine.isVisible(document.getElementById(canvasID), currentJadsdsEngine) }); 
    } 
} 

this.isVisible = function (element, obj) { 
    if (element.offsetWidth === 0 || element.offsetHeight === 0) { 
     currentJadsdsEngine.stop(); 
    } 
    else { 
     var rects = element.getClientRects(); 
     var result = false; 
     var tempClientHeight = document.documentElement.clientHeight; 
     var tempClientWidth = document.documentElement.clientWidth; 

     for (var i = 0, l = rects.length; i < l; i++) { 
      if (rects[i].top + rects[i].height > 0 ? rects[i].top <= tempClientHeight : (rects[i].bottom > 0 && rects[i].bottom <= tempClientHeight) == true) { 
       if (rects[i].left + rects[i].width > 0 ? rects[i].left <= tempClientWidth : (rects[i].right > 0 && rects[i].right <= tempClientWidth) == true) { 
        result = true; 
        break; 
       } 
      } 
     } 

     if (result) { 
      currentJadsdsEngine.resume(); 
     } 
     else { 
      currentJadsdsEngine.stop(); 
     } 
    } 
} 

靈感How do I check if an element is really visible with JavaScript?

+0

嗨薄荷,你可以從你的問題中刪除解決方案的一部分,並將其添加到您的答案。 – bummi 2015-02-12 23:44:47

+0

或只是自己回答你的問題 – nicolallias 2015-02-13 08:07:48

+0

完成,對於麻煩抱歉。 – Peppermint 2015-02-13 09:59:41