Reuse existing canvases from vector render tiles

This commit is contained in:
Andreas Hocevar
2020-01-08 10:42:34 +01:00
parent 5a8df1d4e2
commit 9f4dbd3c35
4 changed files with 27 additions and 4 deletions

View File

@@ -144,6 +144,12 @@ class Tile extends EventTarget {
this.dispatchEvent(EventType.CHANGE); this.dispatchEvent(EventType.CHANGE);
} }
/**
* Called by the tile cache when the tile is removed from the cache due to expiry
*/
release() {
}
/** /**
* @return {string} Key. * @return {string} Key.
*/ */

View File

@@ -15,7 +15,7 @@ class TileCache extends LRUCache {
if (tile.getKey() in usedTiles) { if (tile.getKey() in usedTiles) {
break; break;
} else { } else {
this.pop(); this.pop().release();
} }
} }
} }
@@ -33,6 +33,7 @@ class TileCache extends LRUCache {
this.forEach(function(tile) { this.forEach(function(tile) {
if (tile.tileCoord[0] !== z) { if (tile.tileCoord[0] !== z) {
this.remove(getKey(tile.tileCoord)); this.remove(getKey(tile.tileCoord));
tile.release();
} }
}.bind(this)); }.bind(this));
} }

View File

@@ -18,6 +18,10 @@ import {createCanvasContext2D} from './dom.js';
* @property {number} renderedTileZ * @property {number} renderedTileZ
*/ */
/**
* @type {Array<HTMLCanvasElement>}
*/
const canvasPool = [];
class VectorRenderTile extends Tile { class VectorRenderTile extends Tile {
@@ -107,7 +111,7 @@ class VectorRenderTile extends Tile {
getContext(layer) { getContext(layer) {
const key = getUid(layer); const key = getUid(layer);
if (!(key in this.context_)) { if (!(key in this.context_)) {
this.context_[key] = createCanvasContext2D(); this.context_[key] = createCanvasContext2D(1, 1, canvasPool);
} }
return this.context_[key]; return this.context_[key];
} }
@@ -156,6 +160,16 @@ class VectorRenderTile extends Tile {
load() { load() {
this.getSourceTiles(); this.getSourceTiles();
} }
/**
* @inheritDoc
*/
release() {
for (const key in this.context_) {
canvasPool.push(this.context_[key].canvas);
}
super.release();
}
} }

View File

@@ -7,10 +7,12 @@
* Create an html canvas element and returns its 2d context. * Create an html canvas element and returns its 2d context.
* @param {number=} opt_width Canvas width. * @param {number=} opt_width Canvas width.
* @param {number=} opt_height Canvas height. * @param {number=} opt_height Canvas height.
* @param {Array<HTMLCanvasElement>=} opt_canvasPool Canvas pool to take existing canvas from.
* @return {CanvasRenderingContext2D} The context. * @return {CanvasRenderingContext2D} The context.
*/ */
export function createCanvasContext2D(opt_width, opt_height) { export function createCanvasContext2D(opt_width, opt_height, opt_canvasPool) {
const canvas = document.createElement('canvas'); const canvas = opt_canvasPool && opt_canvasPool.length ?
opt_canvasPool.shift() : document.createElement('canvas');
if (opt_width) { if (opt_width) {
canvas.width = opt_width; canvas.width = opt_width;
} }