Pre-release
AdventureJS Docs Downloads Bundler Devlog Score: 0 Moves: 0
//createImageLookup.js
(function () {
  /* global AdventureJS A */

  var p = AdventureJS.Game.prototype;

  /**
   * <strong>createImageLookup()</strong> is a method
   * used to create an image lookup. Generally used for
   * setting room background images.
   * The function takes one parameter: a generic
   * object containing an array of image id/url pairs.
   *
   * <pre class="display"><code class="language-javascript">MyGame.createImageLookup({
   *   images: [
   *     { id: "desert", src: "images/backgrounds/desert.jpg" },
   *     { id: "sea", src: "images/backgrounds/sea.jpg" },
   *     { id: "mountains", src: "images/backgrounds/mountains.jpg" },
   *     { id: "dungeon", src: "images/backgrounds/dungeon.jpg" },
   *     { id: "throneroom", src: "images/backgrounds/throneroom.jpg" },
   *   ],
   * });
   * </code></pre>
   *
   * The image library is accessible at game.image_lookup.
   * @memberOf AdventureJS.Game
   * @method AdventureJS.Game#createImageLookup
   * @kind function
   * @param {Object} asset A generic object with properties to copy into the image library.
   * @returns {Object} A reference to the image lookup.
   */
  p.createImageLookup = function Game_createImageLookup(properties) {
    const data = properties.images;
    if (data) {
      for (var item in data) {
        // add to lookup
        let src = data[item].src;
        let id = data[item].id;
        // special handling for AdventureJS documentation
        let base = window.AJSDOCS_BASE || this.game.settings.doc_base;
        if (window.AJSDOCS && base) {
          src = base + src;
        }
        let image = (this.image_lookup[id] = {
          id: id,
          src: src,
          width: 0,
          height: 0,
        });
        // create a dom element to load the image into
        // so we can preload/cache it
        let img = document.createElement("img");
        img.dataset.id = id;
        img.src = src;
        img.setAttribute("aria-hidden", true);
        img.setAttribute("loading", "lazy");
        this.game.display.imageCacheEl.appendChild(img);
        img.onload = () => {
          image.width = img.naturalWidth;
          image.height = img.naturalHeight;
        };
      }
    }
    return this.image_lookup;
  };
})();