Skip to content

Commit

Permalink
Fix rotation from the cropper center
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin940726 authored and ajlende committed Aug 1, 2024
1 parent b699f8d commit d0d9963
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
2 changes: 2 additions & 0 deletions packages/components/src/image-cropper/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export const useImageCropper = ( {
x,
y,
} = imageRef.current.getBoundingClientRect();
// Save the initial position and distances from the origin.
memo = {
initial: { x: state.image.x, y: state.image.y },
distances: {
Expand All @@ -72,6 +73,7 @@ export const useImageCropper = ( {
dispatch( {
type: 'ZOOM',
scale,
// Calculate the new position based on the scale from the origin.
position: {
x:
memo.initial.x -
Expand Down
20 changes: 18 additions & 2 deletions packages/components/src/image-cropper/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,20 +180,36 @@ function imageCropperReducer( state: State, action: Action ) {
const nextRadian = degreeToRadian( action.angle + rotations * 90 );
const scaledWidth = image.width * absScale;
const scaledHeight = image.height * absScale;

// Calculate the translation of the image center after the rotation.
// This is needed to rotate from the center of the cropper rather than the
// center of the image.
const deltaRadians = nextRadian - radian;
const rotatedPosition = rotatePoint(
{ x: image.x, y: image.y },
deltaRadians
);

// Calculate the minimum scale to fit the image within the cropper.
// TODO: Optimize the performance?
const minScale =
getMinScale(
nextRadian,
scaledWidth,
scaledHeight,
cropper.width,
cropper.height,
image.x,
image.y
rotatedPosition.x,
rotatedPosition.y
) * absScale;
const nextScale = Math.min( Math.max( absScale, minScale ), 10 );

return {
...state,
image: {
...state.image,
...rotatedPosition,
},
transforms: {
...state.transforms,
angle: action.angle,
Expand Down

0 comments on commit d0d9963

Please sign in to comment.