我想在我的项目中添加裁剪图像功能。因此,我使用react-image-crop npm包。我阅读了文档并编写了代码,但仍然出现了错误。当我从我的电脑中选择一个图像时,它应该出现在localhost:3000上,但图像不会显示在localhost:3000上。当我配置它时,我发现一个错误,即onLoadedImage没有设置开始为null的图像URL。这就是为什么它不显示图像。请帮助我,我怎么能得到的图像网址onLoadedImage,因为我尝试了很多,但没有找到任何解决方案。这是我的代码。
import "./App.css";
import {Form, Button, Container} from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import {useState} from "react";
// import "react-image-crop/dist/ReactCrop.css";
import ReactCrop from "react-image-crop";
import 'react-image-crop/dist/ReactCrop.css';
function App() {
const [srcImg, setSrcImg] = useState(null);
const [image, setImage] = useState(null);
const [crop, setCrop] = useState({aspect: 16 / 9});
const [result, setResult] = useState(null);
const handleImage = async (event) => {
setSrcImg(URL.createObjectURL(event.target.files[0]));
console.log(event.target.files[0]);
};
const getCroppedImg = async () => {
try {
console.log("image")
console.log(image)
const canvas = document.createElement("canvas");
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = crop.width;
canvas.height = crop.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width,
crop.height
);
const base64Image = canvas.toDataURL("image/jpeg", 1);
setResult(base64Image);
console.log(result);
} catch (e) {
console.log(e)
console.log("crop the image");
}
};
const handleSubmit = async (event) => {
event.preventDefault();
console.log(result);
};
// const onLoad = (img)=>{
// console.log("on load function")
// console.log(img)
// setImage(img)
// }
return (
<Container className="container" fluid="md">
<h5 className="header">React Image Crop</h5>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Select Image you want to crop</Form.Label>
<div>
<input type="file" accept="image/*" onChange={handleImage} />
</div>
<div>
{srcImg && (
<div>
<ReactCrop
style={{maxWidth: "50%"}}
src={srcImg}
onImageLoaded={setImage}
crop={crop}
onChange={setCrop}
/>
<Button className="cropButton" onClick={getCroppedImg}>
crop
</Button>
</div>
)}
{result && (
<div>
<img src={result} alt="cropped image" />
</div>
)}
</div>
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</Container>
);
}
export default App;
当我运行我的项目时,在localhost上出现以下屏幕:3000 x1c 0d1x
当我从我的电脑中选择一个图像时,它不会出现在localhost:3000上。它必须出现在屏幕上进行裁剪。请帮我解决这个问题。
2条答案
按热度按时间des4xlb01#
使用
onComplete={setImage}
代替onImageLoaded(setImage)
jdzmm42g2#
你能试着这么做吗?