![](/img/trans.png)
[英]Improve performance of css and javascript with thousands of animated elements
[英]Can I improve the rendering of thousands of elements using JavaScript jQuery?
我正在開發基於Google Maps API的應用程序:基本上,我具有所在國家的郵政編碼,需要顯示它們。
這是一個視頻,顯示了我當前的實現-> https://vid.me/S6PL
地圖的郵政編碼要歸功於google.maps.OverlayView
類,我對該類進行了擴展並創建了一個自定義的PostalCodeOverlay
(以圓圈表示)。 其draw
方法如下:
PostalCodeOverlay.prototype.draw = function() {
var overlayProjection = this.getProjection();
// Handle some positioning stuff here with some properties created before during construction
var center = overlayProjection.fromLatLngToDivPixel(new google.maps.LatLng(this.centerLat, this.centerLng));
var div = this.postalCodeOverlayDiv;
div.style.position = 'absolute';
div.style.left = (center.x - (width/2)) + 'px';
div.style.top = (center.y - (height/2)) + 'px';
div.style["-moz-border-radius"] = "50%";
div.style["-webkit-border-radius"] = "50%";
div.style["border-radius"] = "50%";
// As I show it the first time with an animation and
// the APIs call this method several times (e.g. when
// the zoom level of the map changes), I have a custom
// boolean property that tells me whether it's the first
// time or not
if (!this.justCreated) {
div.style.width = width + "px";
div.style.height = height + "px";
}
else {
this.justCreated = false;
var $postalCodeOverlayDiv = $(div); // here I get a jQuery reference to the div which represents the overlay (the circle).
$postalCodeOverlayDiv.css({
"width": "0",
"height": "0",
"opacity": "0"
});
// Animate it a bit so that it looks nicer when it
// is drawn the first time.
$postalCodeOverlayDiv.animate({
"opacity": "1",
"width": width + "px",
"height": height + "px"
}, 500);
}
};
現在,從視頻中可以看到,縮放級別越高,圓環就越平滑,導致每個視口邊界的郵政編碼密度降低。
但是,當我開始縮小圖像時,您會發現這些漂亮的效果已經消失了,因為現在每個視口范圍內的郵政編碼越來越多(該區域變寬了)。
我通過AJAX從數據庫中獲取郵政編碼(由於在我的數據庫中本地使用了Google Geocoding
API,因此可以對它們進行緩存)。 更改邊界時獲取它們的查詢( map.addListener('bounds_changed', function() {...})
我使用map.addListener('bounds_changed', function() {...})
)非常快,並在發出請求后立即返回。 返回的JSON包含在搜索的特定范圍內的所有郵政編碼,這些郵政編碼是隨着用戶在地圖內移動而計算得出的(如您從視頻中看到的那樣)。 然后,我遍歷此JSON,並為每個條目(代表郵政編碼)創建一個帶有相關信息的new PostalCodeOverlay(...params...)
。
您已經了解的問題是渲染:當渲染成千上萬的元素時,JavaScript引擎缺乏了一點,地圖掛起了。
我可以發布代碼,但我認為不需要在這里,我認為足以向您顯示我使用的視頻和疊加層(無論如何,如果不清楚,請告訴我,我會更新)。
解決這些問題的最佳方法是什么? 當基礎數據集更大時,是否有一種方法可以告訴JavaScript / jQuery更流暢地處理動畫? 或者,也許我不了解某些Google Maps功能,可以在創建的疊加層中利用它們嗎?
無論如何,一些建議將不勝感激。
感謝您的關注。
Google在太多標記上提供了此文檔,以提供建議。 那里有很多可供考慮的選項。
如果在視圖中繪制了數百個元素,您還希望擺脫jQuery動畫。 jQuery動畫涉及計時器上的數千個繪制周期。 將其乘以數百或數千個元素,就遠遠超過了CPU可以有效跟上的速度。 您還可以嘗試使用CSS動畫而不是jQuery動畫,而jQuery動畫可能會變得更有效率。
因此,如果縮放級別超過某個閾值(因此可能會使郵政編碼丟失在視圖中),則跳過動畫並直接設置CSS屬性。
除此之外,您可能會尋求一種更有效的方式來繪制郵政編碼,方法是刪除邊框半徑或簡化某些其他CSS樣式(您不會顯示該div涉及的所有內容,因此我們無法提出更具體的建議) 。 同樣,您只有在縮小到某個閾值以上時才能執行此操作。
並且,對於放大很多的情況,您可能希望跳過重重疊的代碼的渲染,因為它們是如此之小且如此緊密以至於它們始終無法提供很多價值。 這里的挑戰是弄清楚如何做到這一點,同時仍要節省總體CPU。 當縮小超出某個閾值時,您只能在給定的屏幕片段中顯示一個郵政編碼,或者不顯示郵政編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.