imageToSquare.js 1.2 KB

1234567891011121314151617181920212223
  1. import { env } from '../env';
  2. import { createCanvas, createCanvasFromMedia } from './createCanvas';
  3. import { getContext2dOrThrow } from './getContext2dOrThrow';
  4. import { getMediaDimensions } from './getMediaDimensions';
  5. export function imageToSquare(input, inputSize, centerImage) {
  6. if (centerImage === void 0) { centerImage = false; }
  7. var _a = env.getEnv(), Image = _a.Image, Canvas = _a.Canvas;
  8. if (!(input instanceof Image || input instanceof Canvas)) {
  9. throw new Error('imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement');
  10. }
  11. var dims = getMediaDimensions(input);
  12. var scale = inputSize / Math.max(dims.height, dims.width);
  13. var width = scale * dims.width;
  14. var height = scale * dims.height;
  15. var targetCanvas = createCanvas({ width: inputSize, height: inputSize });
  16. var inputCanvas = input instanceof Canvas ? input : createCanvasFromMedia(input);
  17. var offset = Math.abs(width - height) / 2;
  18. var dx = centerImage && width < height ? offset : 0;
  19. var dy = centerImage && height < width ? offset : 0;
  20. getContext2dOrThrow(targetCanvas).drawImage(inputCanvas, dx, dy, width, height);
  21. return targetCanvas;
  22. }
  23. //# sourceMappingURL=imageToSquare.js.map