fix: CropModal

This commit is contained in:
IlyaDoronin 2023-09-13 17:14:27 +03:00
parent f4e0007ed1
commit aa3e3bbe60
5 changed files with 66 additions and 386 deletions

@ -2,7 +2,7 @@ import { useParams } from "react-router-dom";
import { useState } from "react";
import { Typography, Box, useTheme, ButtonBase } from "@mui/material";
import UploadBox from "@ui_kit/UploadBox";
import { CroppingModal } from "@ui_kit/Modal/CroppingModal";
import { CropModal } from "@ui_kit/Modal/CropModal";
import UploadIcon from "../../../assets/icons/UploadIcon";
import * as React from "react";
import { questionStore, updateQuestionsList } from "@root/questions";
@ -67,7 +67,7 @@ export default function UploadImage({ totalIndex }: UploadImageProps) {
/>
</ButtonBase>
<UploadImageModal open={open} onClose={handleClose} imgHC={imgHC} />
<CroppingModal
<CropModal
opened={opened}
onClose={() => setOpened(false)}
picture={listQuestions[quizId][totalIndex].content.back}

@ -3,7 +3,7 @@ import { Box, Typography, useTheme } from "@mui/material";
import AddImage from "@icons/questionsPage/addImage";
import AddVideofile from "@icons/questionsPage/addVideofile";
import { useState } from "react";
import { CroppingModal } from "@ui_kit/Modal/CroppingModal";
import { CropModal } from "@ui_kit/Modal/CropModal";
export default function ImageAndVideoButtons() {
const theme = useTheme();
@ -13,7 +13,7 @@ export default function ImageAndVideoButtons() {
return (
<Box sx={{ display: "flex", alignItems: "center", gap: "12px", mt: "20px", mb: "20px" }}>
<AddImage onClick={() => setOpened(true)} />
<CroppingModal opened={opened} onClose={() => setOpened(false)} />
<CropModal opened={opened} onClose={() => setOpened(false)} />
<Typography
sx={{
fontWeight: 400,

@ -1,6 +1,14 @@
import React, { useState, useRef, FC } from "react";
import React, { useState, useRef, useEffect, FC } from "react";
import ReactCrop, { Crop, PixelCrop } from "react-image-crop";
import { Box, Button, Modal, Slider, Typography, useMediaQuery, useTheme } from "@mui/material";
import {
Box,
Button,
Modal,
Slider,
Typography,
useMediaQuery,
useTheme,
} from "@mui/material";
import { canvasPreview } from "./utils/canvasPreview";
import { useDebounceEffect } from "./utils/useDebounceEffect";
@ -13,9 +21,10 @@ import { CropIcon } from "@icons/CropIcon";
interface Iprops {
opened: boolean;
onClose: React.Dispatch<React.SetStateAction<boolean>>;
picture?: string;
}
export const CropModal2: FC<Iprops> = ({ opened, onClose }) => {
export const CropModal: FC<Iprops> = ({ opened, onClose, picture }) => {
const [imgSrc, setImgSrc] = useState("");
const imgRef = useRef<HTMLImageElement>(null);
@ -31,6 +40,12 @@ export const CropModal2: FC<Iprops> = ({ opened, onClose }) => {
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down(786));
useEffect(() => {
if (picture) {
setImgSrc(picture);
}
}, [picture]);
const styleModal = {
position: "absolute",
top: "50%",
@ -77,7 +92,9 @@ export const CropModal2: FC<Iprops> = ({ opened, onClose }) => {
if (event.target.files && event.target.files.length > 0) {
setCrop(undefined);
const reader = new FileReader();
reader.addEventListener("load", () => setImgSrc(reader.result?.toString() || ""));
reader.addEventListener("load", () =>
setImgSrc(reader.result?.toString() || "")
);
reader.readAsDataURL(event.target.files[0]);
}
};
@ -111,8 +128,18 @@ export const CropModal2: FC<Iprops> = ({ opened, onClose }) => {
useDebounceEffect(
async () => {
if (completedCrop?.width && completedCrop?.height && imgRef.current && previewCanvasRef.current) {
canvasPreview(imgRef.current, previewCanvasRef.current, completedCrop, rotate);
if (
completedCrop?.width &&
completedCrop?.height &&
imgRef.current &&
previewCanvasRef.current
) {
canvasPreview(
imgRef.current,
previewCanvasRef.current,
completedCrop,
rotate
);
}
},
100,
@ -210,10 +237,21 @@ export const CropModal2: FC<Iprops> = ({ opened, onClose }) => {
</Typography>
</Box>
<Box sx={{ display: isMobile ? "block" : "flex", alignItems: "end", justifyContent: "space-between" }}>
<ResetIcon onClick={rotateImage} style={{ marginBottom: "10px", cursor: "pointer" }} />
<Box
sx={{
display: isMobile ? "block" : "flex",
alignItems: "end",
justifyContent: "space-between",
}}
>
<ResetIcon
onClick={rotateImage}
style={{ marginBottom: "10px", cursor: "pointer" }}
/>
<Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>Размер</Typography>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>
Размер
</Typography>
<Slider
sx={styleSlider}
value={width}
@ -226,7 +264,9 @@ export const CropModal2: FC<Iprops> = ({ opened, onClose }) => {
/>
</Box>
<Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>Затемнение</Typography>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>
Затемнение
</Typography>
<Slider
sx={styleSlider}
value={darken}
@ -237,7 +277,14 @@ export const CropModal2: FC<Iprops> = ({ opened, onClose }) => {
/>
</Box>
</Box>
<Box sx={{ marginTop: "40px", width: "100%", display: "flex", justifyContent: "end" }}>
<Box
sx={{
marginTop: "40px",
width: "100%",
display: "flex",
justifyContent: "end",
}}
>
<input
style={{ display: "none", zIndex: "-999" }}
ref={fileInputRef}
@ -268,9 +315,10 @@ export const CropModal2: FC<Iprops> = ({ opened, onClose }) => {
color: "white",
background: "#7E2AEA",
borderRadius: "8px",
marginRight: "6px",
}}
>
<CropIcon style={{ marginRight: "6px" }} />
<CropIcon />
Обрезать
</Button>
</Box>

@ -1,366 +0,0 @@
import React, { FC, useEffect, useRef, useState } from "react";
import { saveAs } from "file-saver";
import ReactCrop, { Crop } from "react-image-crop";
import "react-image-crop/dist/ReactCrop.css";
import {
Box,
Button,
Modal,
Slider,
Typography,
useMediaQuery,
useTheme,
} from "@mui/material";
import quiz from "../../assets/quiz-template-6.png";
import { ResetIcon } from "@icons/ResetIcon";
interface Iprops {
opened: boolean;
onClose: () => void;
picture?: string | ArrayBuffer;
}
export const CroppingModal: FC<Iprops> = ({ opened, onClose, picture }) => {
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down(786));
const style = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: isMobile ? "343px" : "620px",
bgcolor: "background.paper",
boxShadow: 24,
padding: "20px",
borderRadius: "8px",
};
const styleSlider = {
width: isMobile ? "350px" : "250px",
color: "#7E2AEA",
height: "12px",
"& .MuiSlider-track": {
border: "none",
},
"& .MuiSlider-rail": {
backgroundColor: "#F2F3F7",
border: `1px solid "#9A9AAF"`,
},
"& .MuiSlider-thumb": {
height: 26,
width: 26,
border: `6px solid #7E2AEA`,
backgroundColor: "white",
boxShadow: `0px 0px 0px 3px white,
0px 4px 4px 3px #C3C8DD`,
"&:focus, &:hover, &.Mui-active, &.Mui-focusVisible": {
boxShadow: `0px 0px 0px 3px white,
0px 4px 4px 3px #C3C8DD`,
},
},
};
const [src, setSrc] = useState<string | ArrayBuffer | null>(quiz);
const [crop, setCrop] = useState<Crop>({
unit: "px",
y: 0,
x: 0,
width: 100,
height: 100,
});
const [completedCrop, setCompletedCrop] = useState<Crop | null>(null);
const [imageSize, setImageSize] = useState(580);
const [darken, setDarken] = useState(0);
const [croppedImageUrl, setCroppedImageUrl] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (picture) {
setSrc(picture);
}
}, [picture]);
const onCropComplete = (crop: Crop) => {
setCompletedCrop(crop);
if (src) {
getCroppedAndDarkenedImg(src as string, crop, "cropped.jpeg", darken, rotation)
.then((croppedImageUrl) => {
setCroppedImageUrl(croppedImageUrl);
})
.catch((error) => {
console.error("Ошибка при обрезке и затемнении изображения:", error);
});
}
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
if (event.target?.result) {
setSrc(event.target.result);
}
};
reader.readAsDataURL(file);
}
};
const handleDownloadClick = async () => {
if (completedCrop && src) {
const croppedImageUrl = await getCroppedAndDarkenedImg(src, completedCrop, "cropped.jpeg", darken, rotation);
setCroppedImageUrl(croppedImageUrl);
saveAs(croppedImageUrl, "cropped-image.jpeg");
}
};
const [widthImg, setWidthImg] = useState<number>(580);
const getCroppedAndDarkenedImg = (
image: string | ArrayBuffer,
crop: Crop,
fileName: string,
darken: number,
rotation: number
): Promise<string> => {
const img = new Image();
img.src = image as string;
let scaleX = 360 / 580;
let scaleY = 219 / 320;
if (img.naturalWidth) {
scaleX = img.naturalWidth / widthImg;
}
if (img.naturalHeight) {
scaleY = img.naturalHeight / 320;
}
const canvas = document.createElement("canvas");
canvas.width = crop.width!;
canvas.height = crop.height!;
const ctx = canvas.getContext("2d");
if (!ctx) {
throw new Error("Canvas context is null");
}
// Применяем вращение к canvas
ctx.translate(crop.width / 2, crop.height / 2);
ctx.rotate((rotation * Math.PI) / 180);
ctx.translate(-crop.width / 2, -crop.height / 2);
ctx.drawImage(
img,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width,
crop.height
);
const imageData = ctx.getImageData(0, 0, crop.width, crop.height);
const newImageData = imageData.data.map((value, index) => {
if ((index + 1) % 4 === 0) {
return value;
}
return value * (1 - darken / 100);
});
imageData.data.set(newImageData);
ctx.putImageData(imageData, 0, 0);
return new Promise<string>((resolve, reject) => {
canvas.toBlob((blob) => {
if (!blob) {
reject(new Error("Canvas is empty"));
return;
}
const file = new File([blob], fileName, { type: "image/jpeg" });
const imageUrl = window.URL.createObjectURL(file);
resolve(imageUrl);
}, "image/jpeg");
});
};
const [rotation, setRotation] = useState(0);
const rotateImage = () => {
const newRotation = (rotation + 90) % 360;
setRotation(newRotation);
};
const handleSliderChange = (newValue: number) => {
setDarken(newValue);
getCroppedAndDarkenedImg(src as string, completedCrop!, "cropped.jpeg", newValue, rotation);
};
return (
<>
<img
src={croppedImageUrl as string}
alt="Cropped Area"
style={{
position: "absolute",
...completedCrop,
}}
/>
<Modal
open={opened}
onClose={onClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<Box
sx={{
height: "320px",
padding: "10px",
backgroundSize: "cover",
backgroundRepeat: "no-repeat",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<ReactCrop
minWidth={75}
minHeight={75}
maxWidth={580}
maxHeight={320}
crop={crop}
onChange={(newCrop) => setCrop(newCrop)}
onComplete={onCropComplete}
>
{src && (
<img
src={src as string}
onClick={(e) => console.log(e.currentTarget)}
style={{
filter: `brightness(${100 - darken}%)`,
maxWidth: "580px",
transform: `rotate(${rotation}deg)`,
}}
width={580 * (imageSize / 200)}
height={320}
alt="Crop"
/>
)}
</ReactCrop>
</Box>
<Box
sx={{
color: "#7E2AEA",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "16xp",
fontWeight: "600",
marginBottom: "50px",
}}
>
<Typography sx={{ color: "#7E2AEA", lineHeight: "0px" }}>{Math.round(crop.width)}</Typography>x
<Typography sx={{ color: "#7E2AEA", lineHeight: "0px" }}>{Math.round(crop.width)}</Typography>
px
</Box>
<button onClick={rotateImage}>Повернуть на 90 градусов</button>
<Box sx={{ display: isMobile ? "block" : "flex", alignItems: "end", justifyContent: "space-between" }}>
<ResetIcon
onClick={() => {
setCrop((prevCrop: Crop) => ({
...prevCrop,
unit: "px",
x: 210,
y: 10,
width: 210,
height: 300,
}));
setRotation(0);
setDarken(0);
setImageSize(580);
}}
style={{ marginBottom: "10px", cursor: "pointer" }}
/>
<Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>Размер</Typography>
<Slider
sx={styleSlider}
value={imageSize}
min={50}
max={200}
step={1}
onChange={(_, newValue) => {
setImageSize(newValue as number);
setWidthImg(580 * (imageSize / 200));
}}
/>
</Box>
<Box>
<Typography sx={{ color: "#9A9AAF", fontSize: "16px" }}>Затемнение</Typography>
<Slider
sx={styleSlider}
value={darken}
min={0}
max={100}
step={1}
onChange={(_, newValue) => handleSliderChange(newValue as number)}
/>
</Box>
</Box>
<Box sx={{ marginTop: "40px", width: "100%", display: "flex", justifyContent: "end" }}>
<input
ref={fileInputRef}
type="file"
accept="image/*"
id="fileInput"
style={{ display: "none" }}
onChange={handleFileChange}
/>
<Button
onClick={() => fileInputRef.current?.click()}
disableRipple
sx={{
width: "215px",
height: "48px",
color: "#7E2AEA",
borderRadius: "8px",
border: "1px solid #7E2AEA",
marginRight: "10px",
}}
>
Загрузить оригинал
</Button>
<Button
onClick={handleDownloadClick}
disableRipple
sx={{
width: "149px",
height: "48px",
color: "white",
background: "#7E2AEA",
borderRadius: "8px",
}}
>
Обрезать
</Button>
</Box>
</Box>
</Modal>
</>
);
};

@ -1,15 +1,13 @@
import { Box, Button } from "@mui/material";
import { FC, useState } from "react";
import { CroppingModal } from "./CroppingModal";
import { CropModal2 } from "./CropModal2";
import { CropModal } from "./CropModal";
const ImageCrop: FC = () => {
const [opened, setOpened] = useState<boolean>(false);
return (
<Box>
{/* <CroppingModal opened={opened} onClose={() => setOpened(false)} /> */}
<Button onClick={() => setOpened(true)}>Открыть модалку</Button>
<CropModal2 opened={opened} onClose={() => setOpened(false)} />
<CropModal opened={opened} onClose={() => setOpened(false)} />
</Box>
);
};