Working on displaying a rectangle shape in a browser using divs in my React project. Everything works fine, but when I add margin to the parent base
and then draw the boxes, there's some space between the mouse cursor and the actual box.
The same issue occurs if I add a top margin to a base
Check out my code below:
const divRef = useRef<HTMLDivElement>(null);
const [mousedown, setMouseDown] = useState(false);
const [last_mousex, set_last_mousex] = useState(0);
const [last_mousey, set_last_mousey] = useState(0);
const [mousex, set_mousex] = useState(0);
const [mousey, set_mousey] = useState(0);
const [rectx, setrectx] = useState(0);
const [recty, setrecty] = useState(0);
const [rectwidth, setrectwidth] = useState(0);
const [rectheight, setrectheight] = useState(0);
const [visual, setVisualRect] = useState(false);
const mouseDown = (event: any) => {
set_last_mousex(event.clientX);
set_last_mousey(event.clientY);
setMouseDown(true);
};
const mouseMove = (event: any) => {
set_mousex(event.clientX);
set_mousey(event.clientY);
visualRect();
};
const visualRect = () => {
if (mousedown) {
const width = Math.abs(mousex - last_mousex);
const height = Math.abs(mousey - last_mousey);
const rx = mousex < last_mousex ? mousex : last_mousex;
const ry = mousey < last_mousey ? mousey : last_mousey;
rectx !== rx && setrectx(rx);
recty !== ry && setrecty(ry);
rectheight !== height && setrectheight(height);
rectwidth !== width && setrectwidth(width);
setVisualRect(true);
}
};
const mouseUp = () => {
setMouseDown(false);
setVisualRect(false);
};
return (
<div className={"base"}>
<div className={"container"} ref={divRef}>
<div
className={"drawArea"}
onMouseDown={mouseDown}
onMouseUp={mouseUp}
onMouseMove={mouseMove}
>
{visual &&
(<div className={"rectBox"} style={{left: rectx, top: recty, width:rectwidth, height:rectheight}}></div>)
}
</div>
</div>
</div>
);
CSS styling:
.base {
width: 600px;
height: 500px;
/* this margin is causing issue */
margin-left: 200px;
}
.drawArea {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
.rectBox {
position: absolute;
border: 3px solid #581d1d;
}
.container {
height: 500px;
width: 100%;
background-color: rgb(219, 219, 219);
position: relative;
}
View demo on CodeSandbox here