{"version":3,"file":"Image.min.mjs","names":[],"sources":["../../../src/shapes/Image.ts"],"sourcesContent":["import { getFabricDocument, getEnv } from '../env';\nimport type { BaseFilter } from '../filters/BaseFilter';\nimport { getFilterBackend } from '../filters/FilterBackend';\nimport { SHARED_ATTRIBUTES } from '../parser/attributes';\nimport { parseAttributes } from '../parser/parseAttributes';\nimport type {\n  TClassProperties,\n  TCrossOrigin,\n  TSize,\n  Abortable,\n  TOptions,\n} from '../typedefs';\nimport { uid } from '../util/internals/uid';\nimport { createCanvasElementFor } from '../util/misc/dom';\nimport { findScaleToCover, findScaleToFit } from '../util/misc/findScaleTo';\nimport type { LoadImageOptions } from '../util/misc/objectEnlive';\nimport {\n  enlivenObjectEnlivables,\n  enlivenObjects,\n  loadImage,\n} from '../util/misc/objectEnlive';\nimport { parsePreserveAspectRatioAttribute } from '../util/misc/svgParsing';\nimport { classRegistry } from '../ClassRegistry';\nimport { FabricObject, cacheProperties } from './Object/FabricObject';\nimport type { FabricObjectProps, SerializedObjectProps } from './Object/types';\nimport type { ObjectEvents } from '../EventTypeDefs';\nimport { WebGLFilterBackend } from '../filters/WebGLFilterBackend';\nimport { FILL, NONE } from '../constants';\nimport { getDocumentFromElement } from '../util/dom_misc';\nimport type { CSSRules } from '../parser/typedefs';\nimport type { Resize, ResizeSerializedProps } from '../filters/Resize';\nimport type { TCachedFabricObject } from './Object/Object';\nimport { log } from '../util/internals/console';\nimport { escapeXml } from '../util/lang_string';\n\n// @todo Would be nice to have filtering code not imported directly.\n\nexport type ImageSource =\n  | HTMLImageElement\n  | HTMLVideoElement\n  | HTMLCanvasElement;\n\nexport type ParsedPAROffsets = {\n  width: number;\n  height: number;\n  scaleX: number;\n  scaleY: number;\n  offsetLeft: number;\n  offsetTop: number;\n  cropX: number;\n  cropY: number;\n};\n\ninterface UniqueImageProps {\n  srcFromAttribute: boolean;\n  minimumScaleTrigger: number;\n  cropX: number;\n  cropY: number;\n  imageSmoothing: boolean;\n  filters: BaseFilter<string>[];\n  resizeFilter?: Resize;\n}\n\nexport const imageDefaultValues: Partial<TClassProperties<FabricImage>> = {\n  strokeWidth: 0,\n  srcFromAttribute: false,\n  minimumScaleTrigger: 0.5,\n  cropX: 0,\n  cropY: 0,\n  imageSmoothing: true,\n};\n\nexport interface SerializedImageProps extends SerializedObjectProps {\n  src: string;\n  crossOrigin: TCrossOrigin;\n  filters: any[];\n  resizeFilter?: ResizeSerializedProps;\n  cropX: number;\n  cropY: number;\n}\n\nexport interface ImageProps extends FabricObjectProps, UniqueImageProps {}\n\nconst IMAGE_PROPS = ['cropX', 'cropY'] as const;\n\n/**\n * @see {@link http://fabric5.fabricjs.com/fabric-intro-part-1#images}\n */\nexport class FabricImage<\n  Props extends TOptions<ImageProps> = Partial<ImageProps>,\n  SProps extends SerializedImageProps = SerializedImageProps,\n  EventSpec extends ObjectEvents = ObjectEvents,\n>\n  extends FabricObject<Props, SProps, EventSpec>\n  implements ImageProps\n{\n  /**\n   * When calling {@link FabricImage.getSrc}, return value from element src with `element.getAttribute('src')`.\n   * This allows for relative urls as image src.\n   * @since 2.7.0\n   * @type Boolean\n   * @default false\n   */\n  declare srcFromAttribute: boolean;\n\n  /**\n   * private\n   * contains last value of scaleX to detect\n   * if the Image got resized after the last Render\n   * @type Number\n   */\n  protected _lastScaleX = 1;\n\n  /**\n   * private\n   * contains last value of scaleY to detect\n   * if the Image got resized after the last Render\n   * @type Number\n   */\n  protected _lastScaleY = 1;\n\n  /**\n   * private\n   * contains last value of scaling applied by the apply filter chain\n   * @type Number\n   */\n  protected _filterScalingX = 1;\n\n  /**\n   * private\n   * contains last value of scaling applied by the apply filter chain\n   * @type Number\n   */\n  protected _filterScalingY = 1;\n\n  /**\n   * minimum scale factor under which any resizeFilter is triggered to resize the image\n   * 0 will disable the automatic resize. 1 will trigger automatically always.\n   * number bigger than 1 are not implemented yet.\n   * @type Number\n   */\n  declare minimumScaleTrigger: number;\n\n  /**\n   * key used to retrieve the texture representing this image\n   * @since 2.0.0\n   * @type String\n   */\n  declare cacheKey: string;\n\n  /**\n   * Image crop in pixels from original image size.\n   * @since 2.0.0\n   * @type Number\n   */\n  declare cropX: number;\n\n  /**\n   * Image crop in pixels from original image size.\n   * @since 2.0.0\n   * @type Number\n   */\n  declare cropY: number;\n\n  /**\n   * Indicates whether this canvas will use image smoothing when painting this image.\n   * Also influence if the cacheCanvas for this image uses imageSmoothing\n   * @since 4.0.0-beta.11\n   * @type Boolean\n   */\n  declare imageSmoothing: boolean;\n\n  declare preserveAspectRatio: string;\n\n  declare protected src: string;\n\n  declare filters: BaseFilter<string>[];\n  declare resizeFilter: Resize;\n\n  declare _element: ImageSource;\n  declare _filteredEl?: HTMLCanvasElement;\n  declare _originalElement: ImageSource;\n\n  static type = 'Image';\n\n  static cacheProperties = [...cacheProperties, ...IMAGE_PROPS];\n\n  static ownDefaults = imageDefaultValues;\n\n  static getDefaults(): Record<string, any> {\n    return {\n      ...super.getDefaults(),\n      ...FabricImage.ownDefaults,\n    };\n  }\n  /**\n   * Constructor\n   * Image can be initialized with any canvas drawable or a string.\n   * The string should be a url and will be loaded as an image.\n   * Canvas and Image element work out of the box, while videos require extra code to work.\n   * Please check video element events for seeking.\n   * @param {ImageSource | string} element Image element\n   * @param {Object} [options] Options object\n   */\n  constructor(elementId: string, options?: Props);\n  constructor(element: ImageSource, options?: Props);\n  constructor(arg0: ImageSource | string, options?: Props) {\n    super();\n    this.filters = [];\n    Object.assign(this, FabricImage.ownDefaults);\n    this.setOptions(options);\n    this.cacheKey = `texture${uid()}`;\n    this.setElement(\n      typeof arg0 === 'string'\n        ? ((\n            (this.canvas && getDocumentFromElement(this.canvas.getElement())) ||\n            getFabricDocument()\n          ).getElementById(arg0) as ImageSource)\n        : arg0,\n      options,\n    );\n  }\n\n  /**\n   * Returns image element which this instance if based on\n   */\n  getElement() {\n    return this._element;\n  }\n\n  /**\n   * Sets image element for this instance to a specified one.\n   * If filters defined they are applied to new image.\n   * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area.\n   * @param {HTMLImageElement} element\n   * @param {Partial<TSize>} [size] Options object\n   */\n  setElement(element: ImageSource, size: Partial<TSize> = {}) {\n    this.removeTexture(this.cacheKey);\n    this.removeTexture(`${this.cacheKey}_filtered`);\n    this._element = element;\n    this._originalElement = element;\n    this._setWidthHeight(size);\n    if (this.filters.length !== 0) {\n      this.applyFilters();\n    }\n    // resizeFilters work on the already filtered copy.\n    // we need to apply resizeFilters AFTER normal filters.\n    // applyResizeFilters is run more often than normal filters\n    // and is triggered by user interactions rather than dev code\n    if (this.resizeFilter) {\n      this.applyResizeFilters();\n    }\n  }\n\n  /**\n   * Delete a single texture if in webgl mode\n   */\n  removeTexture(key: string) {\n    const backend = getFilterBackend(false);\n    if (backend instanceof WebGLFilterBackend) {\n      backend.evictCachesForKey(key);\n    }\n  }\n\n  /**\n   * Delete textures, reference to elements and eventually JSDOM cleanup\n   */\n  dispose() {\n    super.dispose();\n    this.removeTexture(this.cacheKey);\n    this.removeTexture(`${this.cacheKey}_filtered`);\n    this._cacheContext = null;\n    (\n      ['_originalElement', '_element', '_filteredEl', '_cacheCanvas'] as const\n    ).forEach((elementKey) => {\n      const el = this[elementKey];\n      el && getEnv().dispose(el);\n      // @ts-expect-error disposing\n      this[elementKey] = undefined;\n    });\n  }\n\n  /**\n   * Get the crossOrigin value (of the corresponding image element)\n   */\n  getCrossOrigin(): string | null {\n    return (\n      this._originalElement &&\n      ((this._originalElement as any).crossOrigin || null)\n    );\n  }\n\n  /**\n   * Returns original size of an image\n   */\n  getOriginalSize() {\n    const element = this.getElement() as any;\n    if (!element) {\n      return {\n        width: 0,\n        height: 0,\n      };\n    }\n    return {\n      width: element.naturalWidth || element.width,\n      height: element.naturalHeight || element.height,\n    };\n  }\n\n  /**\n   * @private\n   * @param {CanvasRenderingContext2D} ctx Context to render on\n   */\n  _stroke(ctx: CanvasRenderingContext2D) {\n    if (!this.stroke || this.strokeWidth === 0) {\n      return;\n    }\n    const w = this.width / 2,\n      h = this.height / 2;\n    ctx.beginPath();\n    ctx.moveTo(-w, -h);\n    ctx.lineTo(w, -h);\n    ctx.lineTo(w, h);\n    ctx.lineTo(-w, h);\n    ctx.lineTo(-w, -h);\n    ctx.closePath();\n  }\n\n  /**\n   * Returns object representation of an instance\n   * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n   * @return {Object} Object representation of an instance\n   */\n  toObject<\n    T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n    K extends keyof T = never,\n  >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n    const filters: Record<string, any>[] = [];\n    this.filters.forEach((filterObj) => {\n      filterObj && filters.push(filterObj.toObject());\n    });\n    return {\n      ...super.toObject([...IMAGE_PROPS, ...propertiesToInclude]),\n      src: this.getSrc(),\n      crossOrigin: this.getCrossOrigin(),\n      filters,\n      ...(this.resizeFilter\n        ? { resizeFilter: this.resizeFilter.toObject() }\n        : {}),\n    };\n  }\n\n  /**\n   * Returns true if an image has crop applied, inspecting values of cropX,cropY,width,height.\n   * @return {Boolean}\n   */\n  hasCrop() {\n    return (\n      !!this.cropX ||\n      !!this.cropY ||\n      this.width < this._element.width ||\n      this.height < this._element.height\n    );\n  }\n\n  /**\n   * Returns svg representation of an instance\n   * @return {string[]} an array of strings with the specific svg representation\n   * of the instance\n   */\n  _toSVG() {\n    const imageMarkup: string[] = [],\n      element = this._element,\n      x = -this.width / 2,\n      y = -this.height / 2;\n    let svgString: string[] = [],\n      strokeSvg: string[] = [],\n      clipPath = '',\n      imageRendering = '';\n    if (!element) {\n      return [];\n    }\n    if (this.hasCrop()) {\n      const clipPathId = uid();\n      svgString.push(\n        '<clipPath id=\"imageCrop_' + clipPathId + '\">\\n',\n        '\\t<rect x=\"' +\n          x +\n          '\" y=\"' +\n          y +\n          '\" width=\"' +\n          escapeXml(this.width) +\n          '\" height=\"' +\n          escapeXml(this.height) +\n          '\" />\\n',\n        '</clipPath>\\n',\n      );\n      clipPath = ' clip-path=\"url(#imageCrop_' + clipPathId + ')\" ';\n    }\n    if (!this.imageSmoothing) {\n      imageRendering = ' image-rendering=\"optimizeSpeed\"';\n    }\n    imageMarkup.push(\n      '\\t<image ',\n      'COMMON_PARTS',\n      `xlink:href=\"${escapeXml(this.getSrc(true))}\" x=\"${x - this.cropX}\" y=\"${\n        y - this.cropY\n        // we're essentially moving origin of transformation from top/left corner to the center of the shape\n        // by wrapping it in container <g> element with actual transformation, then offsetting object to the top/left\n        // so that object's center aligns with container's left/top\n      }\" width=\"${\n        element.width || (element as HTMLImageElement).naturalWidth\n      }\" height=\"${\n        element.height || (element as HTMLImageElement).naturalHeight\n      }\"${imageRendering}${clipPath}></image>\\n`,\n    );\n\n    if (this.stroke || this.strokeDashArray) {\n      const origFill = this.fill;\n      this.fill = null;\n      strokeSvg = [\n        `\\t<rect x=\"${x}\" y=\"${y}\" width=\"${escapeXml(this.width)}\" height=\"${escapeXml(\n          this.height,\n        )}\" style=\"${this.getSvgStyles()}\" />\\n`,\n      ];\n      this.fill = origFill;\n    }\n    if (this.paintFirst !== FILL) {\n      svgString = svgString.concat(strokeSvg, imageMarkup);\n    } else {\n      svgString = svgString.concat(imageMarkup, strokeSvg);\n    }\n    return svgString;\n  }\n\n  /**\n   * Returns source of an image\n   * @param {Boolean} filtered indicates if the src is needed for svg\n   * @return {String} Source of an image\n   */\n  getSrc(filtered?: boolean): string {\n    const element = filtered ? this._element : this._originalElement;\n    if (element) {\n      if ((element as HTMLCanvasElement).toDataURL) {\n        return (element as HTMLCanvasElement).toDataURL();\n      }\n\n      if (this.srcFromAttribute) {\n        return element.getAttribute('src') || '';\n      } else {\n        return (element as HTMLImageElement).src;\n      }\n    } else {\n      return this.src || '';\n    }\n  }\n\n  /**\n   * Alias for getSrc\n   * @param filtered\n   * @deprecated\n   */\n  getSvgSrc(filtered?: boolean) {\n    return this.getSrc(filtered);\n  }\n\n  /**\n   * Loads and sets source of an image\\\n   * **IMPORTANT**: It is recommended to abort loading tasks before calling this method to prevent race conditions and unnecessary networking\n   * @param {String} src Source string (URL)\n   * @param {LoadImageOptions} [options] Options object\n   */\n  setSrc(\n    src: string,\n    { crossOrigin, signal }: LoadImageOptions = {},\n  ): Promise<void> {\n    return loadImage(src, { crossOrigin, signal }).then((img) => {\n      typeof crossOrigin !== 'undefined' && this.set({ crossOrigin });\n      this.setElement(img);\n    });\n  }\n\n  /**\n   * Returns string representation of an instance\n   * @return {String} String representation of an instance\n   */\n  toString() {\n    return `#<Image: { src: \"${this.getSrc()}\" }>`;\n  }\n\n  applyResizeFilters() {\n    const filter = this.resizeFilter,\n      minimumScale = this.minimumScaleTrigger,\n      objectScale = this.getTotalObjectScaling(),\n      scaleX = objectScale.x,\n      scaleY = objectScale.y,\n      elementToFilter = this._filteredEl || this._originalElement;\n    if (this.group) {\n      this.set('dirty', true);\n    }\n    if (!filter || (scaleX > minimumScale && scaleY > minimumScale)) {\n      this._element = elementToFilter;\n      this._filterScalingX = 1;\n      this._filterScalingY = 1;\n      this._lastScaleX = scaleX;\n      this._lastScaleY = scaleY;\n      return;\n    }\n    const canvasEl = createCanvasElementFor(elementToFilter),\n      { width, height } = elementToFilter;\n    this._element = canvasEl;\n    this._lastScaleX = filter.scaleX = scaleX;\n    this._lastScaleY = filter.scaleY = scaleY;\n    getFilterBackend().applyFilters(\n      [filter],\n      elementToFilter,\n      width,\n      height,\n      this._element,\n    );\n    this._filterScalingX = canvasEl.width / this._originalElement.width;\n    this._filterScalingY = canvasEl.height / this._originalElement.height;\n  }\n\n  /**\n   * Applies filters assigned to this image (from \"filters\" array) or from filter param\n   * @param {Array} filters to be applied\n   * @param {Boolean} forResizing specify if the filter operation is a resize operation\n   */\n  applyFilters(filters: BaseFilter<string>[] = this.filters || []) {\n    filters = filters.filter((filter) => filter && !filter.isNeutralState());\n    this.set('dirty', true);\n\n    // needs to clear out or WEBGL will not resize correctly\n    this.removeTexture(`${this.cacheKey}_filtered`);\n\n    if (filters.length === 0) {\n      this._element = this._originalElement;\n      // this is unsafe and needs to be rethinkend\n      this._filteredEl = undefined;\n      this._filterScalingX = 1;\n      this._filterScalingY = 1;\n      return;\n    }\n\n    const imgElement = this._originalElement,\n      sourceWidth =\n        (imgElement as HTMLImageElement).naturalWidth || imgElement.width,\n      sourceHeight =\n        (imgElement as HTMLImageElement).naturalHeight || imgElement.height;\n\n    if (this._element === this._originalElement) {\n      // if the _element a reference to _originalElement\n      // we need to create a new element to host the filtered pixels\n      const canvasEl = createCanvasElementFor({\n        width: sourceWidth,\n        height: sourceHeight,\n      });\n      this._element = canvasEl;\n      this._filteredEl = canvasEl;\n    } else if (this._filteredEl) {\n      // if the _element is it own element,\n      // and we also have a _filteredEl, then we clean up _filteredEl\n      // and we assign it to _element.\n      // in this way we invalidate the eventual old resize filtered element\n      this._element = this._filteredEl;\n      this._filteredEl\n        .getContext('2d')!\n        .clearRect(0, 0, sourceWidth, sourceHeight);\n      // we also need to resize again at next renderAll, so remove saved _lastScaleX/Y\n      this._lastScaleX = 1;\n      this._lastScaleY = 1;\n    }\n    getFilterBackend().applyFilters(\n      filters,\n      this._originalElement,\n      sourceWidth,\n      sourceHeight,\n      this._element as HTMLCanvasElement,\n      this.cacheKey,\n    );\n    if (\n      this._originalElement.width !== this._element.width ||\n      this._originalElement.height !== this._element.height\n    ) {\n      this._filterScalingX = this._element.width / this._originalElement.width;\n      this._filterScalingY =\n        this._element.height / this._originalElement.height;\n    }\n  }\n\n  /**\n   * @private\n   * @param {CanvasRenderingContext2D} ctx Context to render on\n   */\n  _render(ctx: CanvasRenderingContext2D) {\n    ctx.imageSmoothingEnabled = this.imageSmoothing;\n    if (this.isMoving !== true && this.resizeFilter && this._needsResize()) {\n      this.applyResizeFilters();\n    }\n    this._stroke(ctx);\n    this._renderPaintInOrder(ctx);\n  }\n\n  /**\n   * Paint the cached copy of the object on the target context.\n   * it will set the imageSmoothing for the draw operation\n   * @param {CanvasRenderingContext2D} ctx Context to render on\n   */\n  drawCacheOnCanvas(\n    this: TCachedFabricObject<FabricImage>,\n    ctx: CanvasRenderingContext2D,\n  ) {\n    ctx.imageSmoothingEnabled = this.imageSmoothing;\n    super.drawCacheOnCanvas(ctx);\n  }\n\n  /**\n   * Decide if the FabricImage should cache or not. Create its own cache level\n   * needsItsOwnCache should be used when the object drawing method requires\n   * a cache step.\n   * Generally you do not cache objects in groups because the group outside is cached.\n   * This is the special Image version where we would like to avoid caching where possible.\n   * Essentially images do not benefit from caching. They may require caching, and in that\n   * case we do it. Also caching an image usually ends in a loss of details.\n   * A full performance audit should be done.\n   * @return {Boolean}\n   */\n  shouldCache() {\n    return this.needsItsOwnCache();\n  }\n\n  _renderFill(ctx: CanvasRenderingContext2D) {\n    const elementToDraw = this._element;\n    if (!elementToDraw) {\n      return;\n    }\n    const scaleX = this._filterScalingX,\n      scaleY = this._filterScalingY,\n      w = this.width,\n      h = this.height,\n      // crop values cannot be lesser than 0.\n      cropX = Math.max(this.cropX, 0),\n      cropY = Math.max(this.cropY, 0),\n      elWidth =\n        (elementToDraw as HTMLImageElement).naturalWidth || elementToDraw.width,\n      elHeight =\n        (elementToDraw as HTMLImageElement).naturalHeight ||\n        elementToDraw.height,\n      sX = cropX * scaleX,\n      sY = cropY * scaleY,\n      // the width height cannot exceed element width/height, starting from the crop offset.\n      sW = Math.min(w * scaleX, elWidth - sX),\n      sH = Math.min(h * scaleY, elHeight - sY),\n      x = -w / 2,\n      y = -h / 2,\n      maxDestW = Math.min(w, elWidth / scaleX - cropX),\n      maxDestH = Math.min(h, elHeight / scaleY - cropY);\n\n    elementToDraw &&\n      ctx.drawImage(elementToDraw, sX, sY, sW, sH, x, y, maxDestW, maxDestH);\n  }\n\n  /**\n   * needed to check if image needs resize\n   * @private\n   */\n  _needsResize() {\n    const scale = this.getTotalObjectScaling();\n    return scale.x !== this._lastScaleX || scale.y !== this._lastScaleY;\n  }\n\n  /**\n   * @private\n   * @deprecated unused\n   */\n  _resetWidthHeight() {\n    this.set(this.getOriginalSize());\n  }\n\n  /**\n   * @private\n   * Set the width and the height of the image object, using the element or the\n   * options.\n   */\n  _setWidthHeight({ width, height }: Partial<TSize> = {}) {\n    const size = this.getOriginalSize();\n    this.width = width || size.width;\n    this.height = height || size.height;\n  }\n\n  /**\n   * Calculate offset for center and scale factor for the image in order to respect\n   * the preserveAspectRatio attribute\n   * @private\n   */\n  parsePreserveAspectRatioAttribute(): ParsedPAROffsets {\n    const pAR = parsePreserveAspectRatioAttribute(\n        this.preserveAspectRatio || '',\n      ),\n      pWidth = this.width,\n      pHeight = this.height,\n      parsedAttributes = { width: pWidth, height: pHeight };\n    let rWidth = this._element.width,\n      rHeight = this._element.height,\n      scaleX = 1,\n      scaleY = 1,\n      offsetLeft = 0,\n      offsetTop = 0,\n      cropX = 0,\n      cropY = 0,\n      offset;\n\n    if (pAR && (pAR.alignX !== NONE || pAR.alignY !== NONE)) {\n      if (pAR.meetOrSlice === 'meet') {\n        scaleX = scaleY = findScaleToFit(this._element, parsedAttributes);\n        offset = (pWidth - rWidth * scaleX) / 2;\n        if (pAR.alignX === 'Min') {\n          offsetLeft = -offset;\n        }\n        if (pAR.alignX === 'Max') {\n          offsetLeft = offset;\n        }\n        offset = (pHeight - rHeight * scaleY) / 2;\n        if (pAR.alignY === 'Min') {\n          offsetTop = -offset;\n        }\n        if (pAR.alignY === 'Max') {\n          offsetTop = offset;\n        }\n      }\n      if (pAR.meetOrSlice === 'slice') {\n        scaleX = scaleY = findScaleToCover(this._element, parsedAttributes);\n        offset = rWidth - pWidth / scaleX;\n        if (pAR.alignX === 'Mid') {\n          cropX = offset / 2;\n        }\n        if (pAR.alignX === 'Max') {\n          cropX = offset;\n        }\n        offset = rHeight - pHeight / scaleY;\n        if (pAR.alignY === 'Mid') {\n          cropY = offset / 2;\n        }\n        if (pAR.alignY === 'Max') {\n          cropY = offset;\n        }\n        rWidth = pWidth / scaleX;\n        rHeight = pHeight / scaleY;\n      }\n    } else {\n      scaleX = pWidth / rWidth;\n      scaleY = pHeight / rHeight;\n    }\n    return {\n      width: rWidth,\n      height: rHeight,\n      scaleX,\n      scaleY,\n      offsetLeft,\n      offsetTop,\n      cropX,\n      cropY,\n    };\n  }\n\n  /**\n   * List of attribute names to account for when parsing SVG element (used by {@link FabricImage.fromElement})\n   * @see {@link http://www.w3.org/TR/SVG/struct.html#ImageElement}\n   */\n  static ATTRIBUTE_NAMES = [\n    ...SHARED_ATTRIBUTES,\n    'x',\n    'y',\n    'width',\n    'height',\n    'preserveAspectRatio',\n    'xlink:href',\n    'href',\n    'crossOrigin',\n    'image-rendering',\n  ];\n\n  /**\n   * Creates an instance of FabricImage from its object representation\n   * @param {Object} object Object to create an instance from\n   * @param {object} [options] Options object\n   * @param {AbortSignal} [options.signal] handle aborting, see https://developer.mozilla.org/en-US/docs/Web/API/AbortController/signal\n   * @returns {Promise<FabricImage>}\n   */\n  static fromObject<T extends TOptions<SerializedImageProps>>(\n    { filters: f, resizeFilter: rf, src, crossOrigin, type, ...object }: T,\n    options?: Abortable,\n  ) {\n    return Promise.all([\n      loadImage(src!, { ...options, crossOrigin }),\n      f && enlivenObjects<BaseFilter<string>>(f, options),\n      // redundant - handled by enlivenObjectEnlivables, but nicely explicit\n      rf ? enlivenObjects<Resize>([rf], options) : [],\n      enlivenObjectEnlivables(object, options),\n    ]).then(([el, filters = [], [resizeFilter], hydratedProps = {}]) => {\n      return new this(el, {\n        ...object,\n        // TODO: passing src creates a difference between image creation and restoring from JSON\n        src,\n        filters,\n        resizeFilter,\n        ...hydratedProps,\n      });\n    });\n  }\n\n  /**\n   * Creates an instance of Image from an URL string\n   * @param {String} url URL to create an image from\n   * @param {LoadImageOptions} [options] Options object\n   * @returns {Promise<FabricImage>}\n   */\n  static fromURL<T extends TOptions<ImageProps>>(\n    url: string,\n    { crossOrigin = null, signal }: LoadImageOptions = {},\n    imageOptions?: T,\n  ): Promise<FabricImage> {\n    return loadImage(url, { crossOrigin, signal }).then(\n      (img) => new this(img, imageOptions),\n    );\n  }\n\n  /**\n   * Returns {@link FabricImage} instance from an SVG element\n   * @param {HTMLElement} element Element to parse\n   * @param {Object} [options] Options object\n   * @param {AbortSignal} [options.signal] handle aborting, see https://developer.mozilla.org/en-US/docs/Web/API/AbortController/signal\n   * @param {Function} callback Callback to execute when Image object is created\n   */\n  static async fromElement(\n    element: HTMLElement,\n    options: Abortable = {},\n    cssRules?: CSSRules,\n  ) {\n    const parsedAttributes = parseAttributes(\n      element,\n      this.ATTRIBUTE_NAMES,\n      cssRules,\n    );\n    return this.fromURL(\n      parsedAttributes['xlink:href'] || parsedAttributes['href'],\n      options,\n      parsedAttributes,\n    ).catch((err) => {\n      log('log', 'Unable to parse Image', err);\n      return null;\n    });\n  }\n}\n\nclassRegistry.setClass(FabricImage);\nclassRegistry.setSVGClass(FabricImage);\n"],"mappings":"8tCA+DA,MAoBM,EAAc,CAAC,QAAS,QAAA,CAK9B,IAAa,EAAb,MAAa,UAKH,CAAA,CAgGR,OAAA,aAAO,CACL,MAAO,CAAA,GACF,MAAM,aAAA,CAAA,GACN,EAAY,YAAA,CAcnB,YAAY,EAA4B,EAAA,CACtC,OAAA,CAAA,EAAA,KAhGQ,cAAc,EAAA,CAAA,EAAA,KAQd,cAAc,EAAA,CAAA,EAAA,KAOd,kBAAkB,EAAA,CAAA,EAAA,KAOlB,kBAAkB,EAAA,CA2E1B,KAAK,QAAU,EAAA,CACf,OAAO,OAAO,KAAM,EAAY,YAAA,CAChC,KAAK,WAAW,EAAA,CAChB,KAAK,SAAW,UAAU,GAAA,GAC1B,KAAK,WACa,OAAT,GAAS,UAET,KAAK,QAAU,EAAuB,KAAK,OAAO,YAAA,CAAA,EACnD,GAAA,EACA,eAAe,EAAA,CACjB,EACJ,EAAA,CAOJ,YAAA,CACE,OAAO,KAAK,SAUd,WAAW,EAAsB,EAAuB,EAAA,CAAA,CACtD,KAAK,cAAc,KAAK,SAAA,CACxB,KAAK,cAAc,GAAG,KAAK,SAAA,WAAA,CAC3B,KAAK,SAAW,EAChB,KAAK,iBAAmB,EACxB,KAAK,gBAAgB,EAAA,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