bonlim
bonlim

Reputation: 193

How to center an image on canvas after rotate the image (Konva.js)

Here's my code on codesandbox, https://codesandbox.io/p/sandbox/adoring-shamir-7q32w7?file=%2Fsrc%2FApp.tsx%3A79%2C26
I'm trying to center an image on canvas after rotating the image.

It places image to image's initial top-left x,y position.
so If the image is rotated, it doesn't come to the center anymore.
If there's any workaround, please share. Thanks.

Upvotes: 0

Views: 121

Answers (2)

bonlim
bonlim

Reputation: 193

I have solved this problem!

  1. before center image, save the rotation value in state and reset the image rotation.
  2. center image
  3. and rotation again with saved rotation value.

https://codesandbox.io/p/sandbox/vigorous-proskuriakova-pgm2ms?file=%2Fsrc%2FApp.tsx%3A103%2C20

Upvotes: 0

lavrton
lavrton

Reputation: 20308

This should work:

function centerImage() {
    const img = imageRef.current;
    if (img) {
      const box = img.getClientRect();
      const offsetX = img.x() - box.x;
      const offsetY = img.y() - box.y;

      img.setAttrs({
        x: CANVAS_SIZE / 2 - box.width / 2 + offsetX,
        y: CANVAS_SIZE / 2 - box.height / 2 + offsetY,
      });
    }
  }

https://codesandbox.io/p/sandbox/recursing-margulis-txffh9?file=%2Fsrc%2FApp.tsx%3A66%2C3-78%2C4

Upvotes: 0

Related Questions