参考来源 https://stackoverflow.com/questions/31193418/html5-canvas-todataurl-returns-blank
https://www.geeksforgeeks.org/how-to-crop-images-in-reactjs/
https://codesandbox.io/s/react-image-crop-demo-with-react-hooks-y831o?file=/src/App.tsx
export const base64Crop = (srcW: number, srcH: number, base64: string, pixelCrop: Crop) => {
return new Promise<string>((resolve) => {
const canvas: HTMLCanvasElement = document.createElement('canvas');
canvas.width = pixelCrop.width;
canvas.height = pixelCrop.height;
let image: HTMLImageElement = document.createElement('img');
image.src = base64;
image.width = srcW;
image.height = srcH;
image.onload = () => {
const ctx = canvas.getContext('2d');
const scaleX = 1;
const scaleY = 1;
const pixelRatio = window.devicePixelRatio;
canvas.width = Math.floor(pixelCrop.width * scaleX * pixelRatio);
canvas.height = Math.floor(pixelCrop.height * scaleY * pixelRatio);
ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(image, 0, 0, srcW, srcH, 0, 0, srcW, srcH);
let s = canvas.toDataURL('image/png');
console.info('s', s.slice(-30));
// return s;
resolve(s);
};
});
};
标签:canvas,const,image,base64,宽高,height,pixelCrop,图片
From: https://www.cnblogs.com/ifnk/p/16744953.html