Wednesday, 8 June 2022

Crop a rectangle with coordinates relative to a rotated image in HTML Canvas

I have the following crop coordinates relative to this rotated image:

crop information relative to the rotated image

The coordinates are relative to the rotated image's height and width. The rotation origin is the centre of the crop rectangle. The rotation of the crop is known.

My goal here is to use the drawImage call and the crop information above and render the following image:

enter image description here

My approach so far is:

  1. Rotate the image first.

  2. Translate the coordinates shown above to be relative to the container.

  3. Call drawImage with the canvas containing the rotated image as the source and the translated coordinates.

    drawImage(rotatedCanvas, rotatedX, rotatedY, cropWidth, cropHeight, 0, 0, width, height)

Issues:

  • I'm not sure how to find the centre point of the crop rectangle given the crop information above. Without this, I cannot set the correct origin for the rotation of the image

  • Without finding this centre point, I cannot use the following code to rotate the coordinates correctly.

// cx origin x, cy origin y
const rotate = (cx: number, cy: number, x: number, y: number, angle: number) => {
  const radians = (Math.PI / 180) * angle;
  const cos = Math.cos(radians);
  const sin = Math.sin(radians);
  const nx = cos * (x - cx) + sin * (y - cy) + cx;
  const ny = cos * (y - cy) - sin * (x - cx) + cy;
  return { nx, ny };
};

To be honest, I'm not sure if I'm going about this the wrong way completely.

Any advice would be greatly appreciated! Many thanks.



from Crop a rectangle with coordinates relative to a rotated image in HTML Canvas

No comments:

Post a Comment