Wait until first load to create icon image

This commit is contained in:
Tim Schaub
2022-07-29 10:35:06 -06:00
parent 459cd51ae2
commit d31f40d6ce
+39 -16
View File
@@ -37,11 +37,13 @@ class IconImage extends EventTarget {
* @private * @private
* @type {HTMLImageElement|HTMLCanvasElement} * @type {HTMLImageElement|HTMLCanvasElement}
*/ */
this.image_ = !image ? new Image() : image; this.image_ = image;
if (crossOrigin !== null) { /**
/** @type {HTMLImageElement} */ (this.image_).crossOrigin = crossOrigin; * @private
} * @type {string|null}
*/
this.crossOrigin_ = crossOrigin;
/** /**
* @private * @private
@@ -85,6 +87,16 @@ class IconImage extends EventTarget {
this.tainted_; this.tainted_;
} }
/**
* @private
*/
initializeImage_() {
this.image_ = new Image();
if (this.crossOrigin_ !== null) {
this.image_.crossOrigin = this.crossOrigin_;
}
}
/** /**
* @private * @private
* @return {boolean} The image canvas is tainted. * @return {boolean} The image canvas is tainted.
@@ -142,6 +154,9 @@ class IconImage extends EventTarget {
* @return {HTMLImageElement|HTMLCanvasElement} Image or Canvas element. * @return {HTMLImageElement|HTMLCanvasElement} Image or Canvas element.
*/ */
getImage(pixelRatio) { getImage(pixelRatio) {
if (!this.image_) {
this.initializeImage_();
}
this.replaceColor_(pixelRatio); this.replaceColor_(pixelRatio);
return this.canvas_[pixelRatio] ? this.canvas_[pixelRatio] : this.image_; return this.canvas_[pixelRatio] ? this.canvas_[pixelRatio] : this.image_;
} }
@@ -166,6 +181,9 @@ class IconImage extends EventTarget {
* @return {HTMLImageElement|HTMLCanvasElement} Image element. * @return {HTMLImageElement|HTMLCanvasElement} Image element.
*/ */
getHitDetectionImage() { getHitDetectionImage() {
if (!this.image_) {
this.initializeImage_();
}
if (!this.hitDetectionImage_) { if (!this.hitDetectionImage_) {
if (this.isTainted_()) { if (this.isTainted_()) {
const width = this.size_[0]; const width = this.size_[0];
@@ -199,19 +217,24 @@ class IconImage extends EventTarget {
* Load not yet loaded URI. * Load not yet loaded URI.
*/ */
load() { load() {
if (this.imageState_ == ImageState.IDLE) { if (this.imageState_ !== ImageState.IDLE) {
this.imageState_ = ImageState.LOADING; return;
try {
/** @type {HTMLImageElement} */ (this.image_).src = this.src_;
} catch (e) {
this.handleImageError_();
}
this.unlisten_ = listenImage(
this.image_,
this.handleImageLoad_.bind(this),
this.handleImageError_.bind(this)
);
} }
if (!this.image_) {
this.initializeImage_();
}
this.imageState_ = ImageState.LOADING;
try {
/** @type {HTMLImageElement} */ (this.image_).src = this.src_;
} catch (e) {
this.handleImageError_();
}
this.unlisten_ = listenImage(
this.image_,
this.handleImageLoad_.bind(this),
this.handleImageError_.bind(this)
);
} }
/** /**