корректная обрезка

This commit is contained in:
Nastya 2024-11-10 21:42:50 +03:00
parent 06e4bed325
commit 8f3facf08a

@ -31,37 +31,25 @@ export function getModifiedImageBlob(
const ctx = canvas.getContext("2d");
if (!ctx) return reject(new Error("No 2d context"));
const scale = 1;
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
const pixelRatio = window.devicePixelRatio;
// Пропорции исходного изображения
const originalWidth = image.width;
const originalHeight = image.height;
canvas.width = Math.floor(crop.width * scaleX * pixelRatio);
canvas.height = Math.floor(crop.height * scaleY * pixelRatio);
// Вычисляем размеры для обрезки в пикселях
const cropWidth = (crop.width / 100) * originalWidth;
const cropHeight = (crop.height / 100) * originalHeight;
const cropX = (crop.x / 100) * originalWidth;
const cropY = (crop.y / 100) * originalHeight;
ctx.scale(pixelRatio, pixelRatio);
ctx.imageSmoothingQuality = "high";
// Устанавливаем размеры канваса
canvas.width = cropWidth;
canvas.height = cropHeight;
const cropX = crop.x * scaleX;
const cropY = crop.y * scaleY;
const centerX = image.naturalWidth / 2;
const centerY = image.naturalHeight / 2;
ctx.translate(-cropX, -cropY);
ctx.translate(centerX, centerY);
ctx.scale(scale, scale);
ctx.translate(-centerX, -centerY);
// Обрезаем изображение
ctx.drawImage(
image,
0,
0,
image.naturalWidth,
image.naturalHeight,
0,
0,
image.naturalWidth,
image.naturalHeight,
cropX, cropY, cropWidth, cropHeight, // Исходная область (x, y, width, height)
0, 0, cropWidth, cropHeight // Целевая область (x, y, width, height)
);
if (darken > 0) {