我正在使用画布来捕捉裁剪后的图像。下面是函数
export const getCroppedImg = (
image: HTMLImageElement,
crop: Crop,
fileName: string
): Promise<Blob> => {
let canvas: HTMLCanvasElement;
let ctx: CanvasRenderingContext2D;
// I m using next.js
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
);
}
}导致ts错误的crop.x, crop.y, crop.width crop.height“对象可能‘未定义’”。我用if(crop)包装了整个逻辑,我尝试了两种不同的方法
canvas.width =crop.width ? crop.width * scaleX : undefined;
canvas.height =crop.height && crop.height * scaleY;"canvas.width“和"canvas.height”警告说
"Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.ts(2322)这是收成:
import { Crop } from "react-image-crop";
interface Crop {
aspect?: number;
x?: number;
y?: number;
width?: number;
height?: number;
unit?: 'px' | '%';
}发布于 2021-10-13 17:40:00
在检查之前,将现有的crop.width和crop.height取出到它们自己的变量中。
您也不能将undefined赋值给canvas.width,或者使用&&有条件地将值赋值给height -请使用if。
如果任何crop属性是未定义的(您将无法正确绘制画布或正确使用drawImage ),则继续任何逻辑看起来都没有意义,因此在这种情况下会抛出错误或尽早返回。
您也没有返回Promise,因此删除Promise<Blob>类型。
export const getCroppedImg = (
image: HTMLImageElement,
crop: Crop,
) => {
const { width, height, x, y } = crop;
if (typeof window === "undefined" || !width || !height || !x || !y) {
// Proceeding further would make no sense;
// can't adjust canvas, or draw the image
// return here, or throw an error or something
throw new Error('Bad argument');
}
const canvas = document.createElement("canvas");
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = width * scaleX;
canvas.height = height * scaleY;
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
ctx.drawImage(
image,
x * scaleX,
y * scaleY,
width * scaleX,
height * scaleY,
0,
0,
width * scaleX,
height * scaleY
);
}发布于 2021-10-13 17:36:18
您在此行中表示canvas.width可能是未定义的:
canvas.width =crop.width ? crop.width * scaleX : undefined;因此,您可以重新处理逻辑,这样就不会出现这种情况。也就是说,有时您比TypeScript编译器知道的更多,所以如果您知道当您需要访问该值时,它永远不会是未定义的,那么您可以断言该值。
canvas.width as number发布于 2021-10-13 17:39:01
为什么在裁剪界面上使用可选字段?
你试过这个吗?:
interface Crop {
aspect: number;
x: number;
y: number;
width: number;
height: number;
unit: 'px' | '%';
}https://stackoverflow.com/questions/69559873
复制相似问题