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

35 Views Asked by At

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.

2

There are 2 best solutions below

1
lavrton On

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

0
bonlim On

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