My current code involves using canvas to capture the cropped image. Below is the function that handles this process:
export const getCroppedImg = (
image: HTMLImageElement,
crop: Crop,
fileName: string
): Promise<Blob> => {
let canvas: HTMLCanvasElement;
let ctx: CanvasRenderingContext2D;
// Employing next.js here
if (typeof window !== "undefined") {
if (crop) {
canvas = document.createElement("canvas");
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width =crop.width ? crop.width * scaleX : undefined;
canvas.height =crop.height && crop.height * scaleY;
ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
ctx.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width * scaleX,
crop.height * scaleY
);
}
}
The use of
crop.x, crop.y, crop.width crop.height
is triggering a TypeScript error stating "Object is possibly 'undefined'". I attempted two different approaches by wrapping the entire logic with an if(crop)
.
canvas.width =crop.width ? crop.width * scaleX : undefined;
canvas.height =crop.height && crop.height * scaleY;
An issue arises with the warnings for "canvas.width" and "canvas.height":
"Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.ts(2322)
Below is the definition for the Crop interface:
import { Crop } from "react-image-crop";
interface Crop {
aspect?: number;
x?: number;
y?: number;
width?: number;
height?: number;
unit?: 'px' | '%';
}