如何解决如何在React中上传的图像上方绘制矩形框
我在将矩形框绘制到上传的图像时遇到了一些问题。现在,我的代码可以让用户在显示的图像上绘制矩形框,但是我不知道如何处理上传的图像。有人可以帮助我使用Reactjs吗?
下面是我的代码,或者您可以在这里的链接中找到,很容易理解我的意思 https://codesandbox.io/s/draw-shape-olnv6?file=/src/index.js
import React,{ useState } from 'react';
import ReactDOM from 'react-dom';
import {
ShapeEditor,ImageLayer,DrawLayer,wrapShape,} from 'react-shape-editor';
import upload_icon from './asset/floor.jpg';
function arrayReplace(arr,index,item) {
return [
...arr.slice(0,index),...(Array.isArray(item) ? item : [item]),...arr.slice(index + 1),];
}
const RectShape = wrapShape(({ width,height }) => (
<rect width={width} height={height} fill="rgba(0,255,0.5)" />
));
let idIterator = 1;
const Editor = () => {
const [items,setItems] = useState([
{ id: '1',x: 20,y: 120,width: 145,height: 140 },{ id: '2',x: 15,y: 0,width: 150,height: 95 },]);
let [file,setFile] = useState(null);
const [{ vectorHeight,vectorWidth },setVectorDimensions] = useState({
vectorHeight: 0,vectorWidth: 0,});
const uploadIconStyle = {
display: 'inline',width: 500,height: 500,};
const fileChangedHandler = (event) => {
let file = event.target.files[0];
let reader = new FileReader();
console.log(file);
reader.onload = function (e) {
setFile(e.target.result);
};
reader.readAsDataURL(event.target.files[0]);
};
return (
<div>
<input
className="btn btn-secondary"
id="fileInput"
type="file"
accept="image/*"
onChange={fileChangedHandler}
/>
<img
src={file}
alt={''}
width="400"
height="400"
text-align="left"
style={{ display: 'block' }}
/>
<ShapeEditor vectorWidth={vectorWidth} vectorHeight={vectorHeight}>
<ImageLayer
// Photo by Sarah Gualtieri on Unsplash
style={uploadIconStyle}
src={upload_icon}
responsive
onLoad={({ naturalWidth,naturalHeight }) => {
setVectorDimensions({
vectorWidth: naturalWidth,vectorHeight: naturalHeight,});
}}
/>
<DrawLayer
onAddShape={({ x,y,width,height }) => {
setItems((currentItems) => [
...currentItems,{ id: `id${idIterator}`,x,height },]);
idIterator += 1;
}}
/>
{items.map((item,index) => {
const { id,height,y } = item;
return (
<RectShape
key={id}
shapeId={id}
height={height}
width={width}
x={x}
y={y}
onChange={(newRect) => {
setItems((currentItems) =>
arrayReplace(currentItems,{
...item,...newRect,})
);
}}
onDelete={() => {
setItems((currentItems) =>
arrayReplace(currentItems,[])
);
}}
/>
);
})}
</ShapeEditor>
</div>
);
};
const rootElement = document.getElementById('root');
ReactDOM.render(<Editor />,rootElement);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。