Обрезка фото через react-image-crop
Не селен в canvas от слова совсем.... Народ, подскажите пожалуйста. Когда открываю фото в полный размер он отлично его режет, но когда задаю размер фото для отображения его на странице функция обрезает его очень странно. Причем одни фотки ок другие вообще странно
image: HTMLImageElement,
canvas: HTMLCanvasElement,
crop: PixelCrop,
scale,
rotate = 0,
) {
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('No 2d context');
}
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
const pixelRatio = window.devicePixelRatio;
canvas.width = Math.floor(crop.width * pixelRatio);
canvas.height = Math.floor(crop.height * pixelRatio);
ctx.imageSmoothingQuality = 'high';
const cropX = crop.x * scaleX;
const cropY = crop.y * scaleY;
const rotateRads = rotate * TO_RADIANS;
const centerX = image.naturalWidth / 2;
const centerY = image.naturalHeight / 2;
ctx.save();
ctx.translate(-cropX, -cropY);
ctx.translate(centerX, centerY);
ctx.rotate(rotateRads);
if (scale === -1.1) {
ctx.scale(-1, 1);
} else {
ctx.scale(1, 1);
}
ctx.translate(-centerX, -centerY);
ctx.drawImage(
image,
0,
0,
image.naturalWidth,
image.naturalHeight,
0,
0,
image.naturalWidth,
image.naturalHeight,
);
ctx.restore();
}```