【发布时间】:2021-10-14 01:43:13
【问题描述】:
我正在使用画布来捕捉裁剪后的图像。这是函数
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
);
}
}
crop.x, crop.y, crop.width crop.height 导致 ts 错误“对象可能是‘未定义’”。我用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' | '%';
}
【问题讨论】:
标签: typescript canvas next.js