Skip to content

Commit

Permalink
feat: fill image. (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
seven7seven authored Nov 29, 2024
1 parent 4b73007 commit 40a9a84
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
27 changes: 27 additions & 0 deletions core/src/replacer/fill-image.ts
Original file line number Diff line number Diff line change
@@ -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
});
}
1 change: 1 addition & 0 deletions core/src/replacer/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './fit-image';
export * from './mce-canvas-replacer';
export * from './stretch-image';
export * from './fill-image';
6 changes: 5 additions & 1 deletion core/src/replacer/mce-canvas-replacer.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<void> {
public async replaceRectToImage(layer: MceLayer, sourceImage: HTMLImageElement | string, mode: 'stretch' | 'fit' | 'fill'): Promise<void> {
const rect = this.objects[layer.realIndex] as MceRect;
if (!rect.visible) {
// If the layer is hidden, do nothing.
Expand All @@ -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}`);
}
Expand Down

0 comments on commit 40a9a84

Please sign in to comment.