diff --git a/core/src/replacer/fill-image.ts b/core/src/replacer/fill-image.ts new file mode 100644 index 0000000..b8356e1 --- /dev/null +++ b/core/src/replacer/fill-image.ts @@ -0,0 +1,27 @@ +import { MceImage, MceRect } from '../shapes'; + +export function fillImage(rect: MceRect, sourceImage: HTMLImageElement): MceImage { + const scale = Math.min(rect.width / sourceImage.width, rect.height / sourceImage.height); + const cropWidth = rect.width / scale; + const cropHeight = rect.height / scale; + + // Center the crop area + const cropY = Math.max(0, (sourceImage.height - cropHeight) / 2); + const cropX = Math.max(0, (sourceImage.width - cropWidth) / 2); + + // Center the image in the rect + const left = rect.left + (rect.width - sourceImage.width * scale) / 2; + const top = rect.top + (rect.height - sourceImage.height * scale) / 2; + + return new MceImage(sourceImage, { + angle: rect.angle, + left, + top, + width: cropWidth, + height: cropHeight, + scaleX: scale, + scaleY: scale, + cropY, + cropX + }); +} diff --git a/core/src/replacer/index.ts b/core/src/replacer/index.ts index 510baea..a033d75 100644 --- a/core/src/replacer/index.ts +++ b/core/src/replacer/index.ts @@ -1,3 +1,4 @@ export * from './fit-image'; export * from './mce-canvas-replacer'; export * from './stretch-image'; +export * from './fill-image'; diff --git a/core/src/replacer/mce-canvas-replacer.ts b/core/src/replacer/mce-canvas-replacer.ts index 3ed5fcf..0c2f3a2 100644 --- a/core/src/replacer/mce-canvas-replacer.ts +++ b/core/src/replacer/mce-canvas-replacer.ts @@ -1,6 +1,7 @@ import { MceImage, MceRect, MceTextbox } from '../shapes'; import { fitImage } from './fit-image'; import { stretchImage } from './stretch-image'; +import { fillImage } from './fill-image'; import { MceStaticCanvas } from '../mce-static-canvas'; import { Object as FabricObject } from 'fabric'; import { loadImage } from './load-image'; @@ -36,7 +37,7 @@ export class MceCanvasReplacer { * @param mode Mode of fitting image to the rectangle. * @returns Promise that resolves when the rect is replaced. */ - public async replaceRectToImage(layer: MceLayer, sourceImage: HTMLImageElement | string, mode: 'stretch' | 'fit'): Promise { + public async replaceRectToImage(layer: MceLayer, sourceImage: HTMLImageElement | string, mode: 'stretch' | 'fit' | 'fill'): Promise { const rect = this.objects[layer.realIndex] as MceRect; if (!rect.visible) { // If the layer is hidden, do nothing. @@ -54,6 +55,9 @@ export class MceCanvasReplacer { case 'fit': image = fitImage(rect, sourceImage); break; + case 'fill': + image = fillImage(rect, sourceImage); + break; default: throw new Error(`Unknown mode: ${mode}`); }