drag an image with the cursor using react

832 views Asked by At

i have a div with a background image and when i press and hold down on it a can drag the image within the div via setting the background position to the cursor position

const [mousePos, setMousePos] = useState({});
const [imageCenter, setImageCenter] = useState(`center`);
const [onImage, setOnImage] = useState(false);

useEffect(() => {
const handleMouseMove = (event) => {
  setMousePos({ x: event.clientX, y: event.clientY });
};

window.addEventListener('mousemove', handleMouseMove);

return () => {
  window.removeEventListener(
    'mousemove',
    handleMouseMove
  );
};
}, []);

the div

<div style={{height:`100%`,width:`100vw`,background:`url(${displayImage}) no-repeat ${imageCenter} / cover`,position:`relative`}} onMouseDown={() => setOnImage(true)} onMouseUp={() => setOnImage(false)} onMouseMove={() => {
        if (onImage) {
          setImageCenter(`${mousePos.x - (window.innerWidth / 2)}px ${mousePos.y - (window.innerHeight / 2)}px`)
        }
      }}>
      </div>

but when i drag the image the cursor always goes to the center of the image no matter where i left the image inside the frame, i want to make it so that when i hold down and move the image and then press again the focal point is where i pressed not the center of the image

1

There are 1 answers

0
eitan On

i was able to fix it, the image is dragged by the cursor position

const [mousePos, setMousePos] = useState({});
const [imageCenter, setImageCenter] = useState(`0px, 0px`);
const [onImage, setOnImage] = useState(false);
const [distanceX, setDistanceX] = useState(null);
const [distanceY, setDistanceY] = useState(null);

useEffect(() => {
const handleMouseMove = (event) => {
  setMousePos({ x: event.clientX, y: event.clientY });
};

window.addEventListener('mousemove', handleMouseMove);

return () => {
  window.removeEventListener(
    'mousemove',
    handleMouseMove
  );
};
}, []);

the div

<div style={{height:`100%`,width:`100vw`,backgroundImage:`url(${displayImage})`,backgroundRepeat:`no-repeat`,backgroundPosition:imageCenter,backgroundSize:`cover`,position:`relative`}} onMouseDown={e => {
        setOnImage(true)
        setDistanceX(mousePos.x - parseInt(window.getComputedStyle(e.target).getPropertyValue("background-position").split(' ')[0].slice(0, -2)))
        setDistanceY(mousePos.y - parseInt(window.getComputedStyle(e.target).getPropertyValue("background-position").split(' ')[1].slice(0, -2)))
      }} onMouseUp={() => setOnImage(false)} onMouseMove={e => {
        if (onImage) {
          setImageCenter(`${mousePos.x - distanceX}px ${mousePos.y - distanceY}px`)
        }
      }}>
      </div>