Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@anu3ev/fabric-image-editor",
"version": "0.5.32",
"version": "0.5.33",
"description": "JavaScript image editor built on FabricJS, allowing you to create instances with an integrated montage area and providing an API to modify and manage state.",
"module": "dist/main.js",
"files": [
Expand Down
59 changes: 40 additions & 19 deletions src/editor/image-manager/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@ export type ResizeImageToBoundariesOptions = {
dataURL: string,
sizeType?: 'max' | 'min',
contentType?: string,
quality?: number,
maxWidth?: number,
maxHeight?: number,
minWidth?: number,
minHeight?: number,
asBase64?: boolean,
asBlob?: boolean
asBlob?: boolean,
emitMessage?: boolean
}

export type ExportObjectAsImageFileParameters = {
Expand Down Expand Up @@ -354,6 +356,8 @@ export default class ImageManager {
* @param options.minHeight - минимальная высота (по умолчанию CANVAS_MIN_HEIGHT)
* @param options.asBase64 - вернуть base64 вместо Blob
* @param options.emitMessage - выводить предупреждение в случае ресайза
* @param options.contentType - тип контента
* @param options.quality - качество изображения от 0 до 1 (для JPEG/WebP)
* @returns возвращает Promise с Blob или base64 в зависимости от опций
*/
public async resizeImageToBoundaries(
Expand Down Expand Up @@ -516,15 +520,19 @@ export default class ImageManager {
return data
}

// Получаем blob из клонированного канваса
// Получаем blob из клонированного канваса в нужном формате
const blob: Blob = await new Promise((resolve, reject) => {
tmpCanvas.getElement().toBlob((canvasBlob) => {
if (canvasBlob) {
resolve(canvasBlob)
} else {
reject(new Error('Failed to create Blob from canvas'))
}
})
tmpCanvas.getElement().toBlob(
(canvasBlob) => {
if (canvasBlob) {
resolve(canvasBlob)
} else {
reject(new Error('Failed to create Blob from canvas'))
}
},
adjustedContentType,
1
)
})

// Уничтожаем клон
Expand All @@ -545,9 +553,14 @@ export default class ImageManager {

// Создаём bitmap из blob, отправляем в воркер и получаем dataURL
const bitmap = await createImageBitmap(blob)

const dataUrl = await workerManager.post(
'toDataURL',
{ contentType: adjustedContentType, quality: 1, bitmap },
{
contentType: adjustedContentType,
quality: 1,
bitmap
},
[bitmap]
)

Expand Down Expand Up @@ -660,44 +673,52 @@ export default class ImageManager {
exportAsBlob = false
} = options

const processedFileName = fileName ?? `image.${object.format}`
const processedContentType = contentType ?? object.contentType ?? 'image/png'

const { canvas, workerManager } = this.editor

const activeObject = object || canvas.getActiveObject()
const fallbackContentType = contentType ?? 'image/png'
const fallbackFormat = ImageManager.getFormatFromContentType(fallbackContentType) || 'png'
const fallbackFileName = fileName ?? `image.${fallbackFormat}`

if (!activeObject) {
this.editor.errorManager.emitError({
origin: 'ImageManager',
method: 'exportObjectAsImageFile',
code: 'NO_OBJECT_SELECTED',
message: 'Не выбран объект для экспорта',
data: { contentType: processedContentType, fileName: processedFileName, exportAsBase64, exportAsBlob }
data: { contentType: fallbackContentType, fileName: fallbackFileName, exportAsBase64, exportAsBlob }
})

return null
}

try {
const format = ImageManager.getFormatFromContentType(processedContentType)
const { contentType: objectContentType, format: objectFormat = '' } = activeObject as {
contentType?: string
format?: string
}
const processedContentType = contentType ?? objectContentType ?? 'image/png'
const format = ImageManager.getFormatFromContentType(processedContentType)
|| objectFormat
|| 'png'
const processedFileName = fileName ?? `image.${format}`

try {
if (format === 'svg') {
// Конвертируем fabric.Object в SVG-строку
const svgString = activeObject.toSVG()

const svg = ImageManager._exportSVGStringAsFile(svgString, {
exportAsBase64,
exportAsBlob,
fileName
fileName: processedFileName
})

const data = {
object: activeObject,
image: svg,
format,
contentType: 'image/svg+xml',
fileName: fileName.replace(/\.[^/.]+$/, '.svg')
fileName: processedFileName.replace(/\.[^/.]+$/, '.svg')
}

canvas.fire('editor:object-exported', data)
Expand Down Expand Up @@ -755,7 +776,7 @@ export default class ImageManager {
}

// Преобразуем Blob в File
const file = new File([activeObjectBlob], fileName, { type: processedContentType })
const file = new File([activeObjectBlob], processedFileName, { type: processedContentType })

const data = {
object: activeObject,
Expand Down
18 changes: 16 additions & 2 deletions src/editor/worker-manager/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,16 @@ self.onmessage = async(e: MessageEvent): Promise<void> => {
try {
switch (action) {
case 'resizeImage': {
const { dataURL, maxWidth, maxHeight, minWidth, minHeight, contentType, quality, sizeType } = payload
const {
dataURL,
maxWidth,
maxHeight,
minWidth,
minHeight,
contentType,
quality,
sizeType
} = payload
const imgBitmap = await createImageBitmap(await (await fetch(dataURL)).blob())

// вычисляем новый размер
Expand Down Expand Up @@ -38,7 +47,12 @@ self.onmessage = async(e: MessageEvent): Promise<void> => {
}

case 'toDataURL': {
const { bitmap, contentType, quality, returnBlob } = payload
const {
bitmap,
contentType,
quality,
returnBlob
} = payload
const { width, height } = bitmap

// рисуем изображение в offscreen
Expand Down