hey sorry for the bad english i hope you guys understand what i mean.i have this code below but i get error and ‘image’ is of type ‘unknown’.do you guys know how to solve this error? please tell me how to solve this error and please do tell me in detail what need to change or add because i am really new to typescript
const createImage = (url:any) =>
new Promise((resolve, reject) => {
const image = new Image();
image.addEventListener("load", () => resolve(image));
image.addEventListener("error", error => reject(error));
image.setAttribute("crossOrigin", "anonymous"); // needed to avoid cross-origin issues on CodeSandbox
image.src = url;
});
function getRadianAngle(degreeValue:any) {
return (degreeValue * Math.PI) / 180;
}
export default async function getCroppedImg(imageSrc:any, pixelCrop:any,rotation = 0) {
const image = await createImage(imageSrc);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) {
return;
}
const maxSize = Math.max(image.width, image.height);
const safeArea = 2 * ((maxSize / 2) * Math.sqrt(2));
canvas.width = safeArea;
canvas.height = safeArea;
ctx.translate(safeArea / 2, safeArea / 2);
ctx.rotate(getRadianAngle(rotation));
ctx.translate(-safeArea / 2, -safeArea / 2);
ctx.fillStyle = "#DCDCDC";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(
image
safeArea / 2 - image.width * 0.5,
safeArea / 2 - image.height * 0.5
);
const data = ctx.getImageData(0, 0, safeArea, safeArea);
canvas.width = pixelCrop.width;
canvas.height = pixelCrop.height;
// paste generated rotate image with correct offsets for x,y crop values.
ctx.putImageData(
data,
Math.round(0 - safeArea / 2 + image.width * 0.5 - pixelCrop.x),
Math.round(0 - safeArea / 2 + image.height * 0.5 - pixelCrop.y)
);
return new Promise(resolve => {
canvas.toBlob(file => {
resolve(file);
}, "image/png");
});
}
>Solution :
You have to type the return of Promise, otherwise it will becomes unknown:
const createImage = (url: string) =>
new Promise<HTMLImageElement>((resolve, reject) => {
// ...
});
and also in the last line:
return new Promise<Blob | null>(resolve => {
canvas.toBlob(file => {
resolve(file);
}, "image/png");
});