Skip to content

Commit 40a9a84

Browse files
authored
feat: fill image. (#8)
1 parent 4b73007 commit 40a9a84

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

core/src/replacer/fill-image.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { MceImage, MceRect } from '../shapes';
2+
3+
export function fillImage(rect: MceRect, sourceImage: HTMLImageElement): MceImage {
4+
const scale = Math.min(rect.width / sourceImage.width, rect.height / sourceImage.height);
5+
const cropWidth = rect.width / scale;
6+
const cropHeight = rect.height / scale;
7+
8+
// Center the crop area
9+
const cropY = Math.max(0, (sourceImage.height - cropHeight) / 2);
10+
const cropX = Math.max(0, (sourceImage.width - cropWidth) / 2);
11+
12+
// Center the image in the rect
13+
const left = rect.left + (rect.width - sourceImage.width * scale) / 2;
14+
const top = rect.top + (rect.height - sourceImage.height * scale) / 2;
15+
16+
return new MceImage(sourceImage, {
17+
angle: rect.angle,
18+
left,
19+
top,
20+
width: cropWidth,
21+
height: cropHeight,
22+
scaleX: scale,
23+
scaleY: scale,
24+
cropY,
25+
cropX
26+
});
27+
}

core/src/replacer/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * from './fit-image';
22
export * from './mce-canvas-replacer';
33
export * from './stretch-image';
4+
export * from './fill-image';

core/src/replacer/mce-canvas-replacer.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { MceImage, MceRect, MceTextbox } from '../shapes';
22
import { fitImage } from './fit-image';
33
import { stretchImage } from './stretch-image';
4+
import { fillImage } from './fill-image';
45
import { MceStaticCanvas } from '../mce-static-canvas';
56
import { Object as FabricObject } from 'fabric';
67
import { loadImage } from './load-image';
@@ -36,7 +37,7 @@ export class MceCanvasReplacer {
3637
* @param mode Mode of fitting image to the rectangle.
3738
* @returns Promise that resolves when the rect is replaced.
3839
*/
39-
public async replaceRectToImage(layer: MceLayer, sourceImage: HTMLImageElement | string, mode: 'stretch' | 'fit'): Promise<void> {
40+
public async replaceRectToImage(layer: MceLayer, sourceImage: HTMLImageElement | string, mode: 'stretch' | 'fit' | 'fill'): Promise<void> {
4041
const rect = this.objects[layer.realIndex] as MceRect;
4142
if (!rect.visible) {
4243
// If the layer is hidden, do nothing.
@@ -54,6 +55,9 @@ export class MceCanvasReplacer {
5455
case 'fit':
5556
image = fitImage(rect, sourceImage);
5657
break;
58+
case 'fill':
59+
image = fillImage(rect, sourceImage);
60+
break;
5761
default:
5862
throw new Error(`Unknown mode: ${mode}`);
5963
}

0 commit comments

Comments
 (0)