Ninini
Ninini

Reputation: 81

How to update the x and y coordinates of the image after being dragged to a different position?

I have a konva canvas with images where I can add images to the canvas and drag them around. The images are a DOM elements that can be dragged onto the canvas, like here:

{loadImages.map(image => (
  <img id="img" className="img"
  src={image.image}
  width="200"
  height="200"
  onDragStart={(e) => {
    dragUrl.current = e.target.src;}}
/>
))}
    
    <div
        onDrop={(e) => {
          e.preventDefault();
          // register event position
          stageEl.current.setPointersPositions(e);
          // add image
          setImages(
            images.concat([
              {
                ...stageEl.current.getPointerPosition(),
                src: dragUrl.current,
                id: `img${images.length + 1}`
              },
            ])
          );
          socket.emit("canvas-data", [
            {
              ...stageEl.current.getPointerPosition(),
              src: dragUrl.current,
              dataType: "Image"
            },
          ])
        }}
        onDragOver={(e) => {
          e.preventDefault();
        }
        }
      >

Whenever the image is dragged onto the canvas, the image gets added to an array called images. Each image gets its own x and y coordinates (depending on where the image was dragged), source (what image it is) and id (which grows by 1 each time a new image gets added.)

And below I have the onDragEnd event where I want to adjust the x and y coordinates of the current image being dragged (so in the array images) after at the onDragEnd event:

  const URLImage = ({image}) => {
    const [img] = useImage(image.src);
    return (
      <Image
        image = {img}
        x = {image.x}
        y = {image.y}

        offsetX = {50}
        offsetY = {50}

        width={200}
        height={200}
        draggable
        onDragEnd={e => {
          
        }}

      />
    );
  };

Any ideas on how to achieve this?

Upvotes: 3

Views: 933

Answers (1)

lavrton
lavrton

Reputation: 20373

You can use e.target to access updated properties of the node.,

const URLImage = ({ image, onChange}) => {
    const [img] = useImage(image.src);
    return (
      <Image
        image = {img}
        x = {image.x}
        y = {image.y}
        width={200}
        height={200}
        draggable
        onDragEnd={e => {
          onChange({ x: e.targe.x(), y: e.target.y()})
        }}
      />
    );
};

And then update state of your app:

<URLImage
  image={image}
  onChange={(newProps) => {
    const newImage = { ...image, ...newProps};
    // copy array of state
    const newImages = images.slice();
    newImages[index] = newImage;
    setImages(newImages);
  }}
/>

Upvotes: 1

Related Questions