UNPKG

fabric

Version:

Object model for HTML5 canvas, and SVG-to-canvas parser. Backed by jsdom and node-canvas.

1 lines 37.6 kB
{"version":3,"file":"Image.min.mjs","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';\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, Record<string, any>>[];\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, Record<string, any>>[];\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 this.width +\n '\" height=\"' +\n 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=\"${this.getSvgSrc(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=\"${this.width}\" height=\"${\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(src: string, { crossOrigin, signal }: LoadImageOptions = {}) {\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(\n filters: BaseFilter<string, Record<string, any>>[] = this.filters || [],\n ) {\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"],"names":["imageDefaultValues","strokeWidth","srcFromAttribute","minimumScaleTrigger","cropX","cropY","imageSmoothing","IMAGE_PROPS","FabricImage","FabricObject","getDefaults","super","ownDefaults","constructor","arg0","options","_defineProperty","this","filters","Object","assign","setOptions","cacheKey","uid","setElement","canvas","getDocumentFromElement","getElement","getFabricDocument","getElementById","_element","element","size","arguments","length","undefined","removeTexture","_originalElement","_setWidthHeight","applyFilters","resizeFilter","applyResizeFilters","key","backend","getFilterBackend","WebGLFilterBackend","evictCachesForKey","dispose","_cacheContext","forEach","elementKey","el","getEnv","getCrossOrigin","crossOrigin","getOriginalSize","width","naturalWidth","height","naturalHeight","_stroke","ctx","stroke","w","h","beginPath","moveTo","lineTo","closePath","toObject","propertiesToInclude","filterObj","push","src","getSrc","hasCrop","_toSVG","imageMarkup","x","y","svgString","strokeSvg","clipPath","imageRendering","clipPathId","getSvgSrc","strokeDashArray","origFill","fill","getSvgStyles","paintFirst","FILL","concat","filtered","toDataURL","getAttribute","setSrc","signal","loadImage","then","img","set","toString","filter","minimumScale","objectScale","getTotalObjectScaling","scaleX","scaleY","elementToFilter","_filteredEl","group","_filterScalingX","_filterScalingY","_lastScaleX","_lastScaleY","canvasEl","createCanvasElementFor","isNeutralState","imgElement","sourceWidth","sourceHeight","getContext","clearRect","_render","imageSmoothingEnabled","isMoving","_needsResize","_renderPaintInOrder","drawCacheOnCanvas","shouldCache","needsItsOwnCache","_renderFill","elementToDraw","Math","max","elWidth","elHeight","sX","sY","sW","min","sH","maxDestW","maxDestH","drawImage","scale","_resetWidthHeight","parsePreserveAspectRatioAttribute","pAR","preserveAspectRatio","pWidth","pHeight","parsedAttributes","offset","rWidth","rHeight","offsetLeft","offsetTop","alignX","NONE","alignY","meetOrSlice","findScaleToFit","findScaleToCover","fromObject","_ref","f","rf","type","object","Promise","all","enlivenObjects","enlivenObjectEnlivables","_ref2","hydratedProps","fromURL","url","imageOptions","fromElement","cssRules","parseAttributes","ATTRIBUTE_NAMES","catch","err","log","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":"mqCA8DO,MAAMA,EAA6D,CACxEC,YAAa,EACbC,kBAAkB,EAClBC,oBAAqB,GACrBC,MAAO,EACPC,MAAO,EACPC,gBAAgB,GAcZC,EAAc,CAAC,QAAS,SAKvB,MAAMC,UAKHC,EAgGR,kBAAOC,GACL,MAAO,IACFC,MAAMD,iBACNF,EAAYI,YAEnB,CAYAC,WAAAA,CAAYC,EAA4BC,GACtCJ,QAtGFK,qBAMwB,GAExBA,qBAMwB,GAExBA,yBAK4B,GAE5BA,yBAK4B,GA2E1BC,KAAKC,QAAU,GACfC,OA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