I've been beating my head against the wall with this problem for days.
After much searching and experimenting with various ratio algorithms, I realise the maths part of my brain is missing or dead.
I'm working on a cropping tool.
After selecting a rectangular crop area over the image, I'd like to zoom in on the crop area segment.
To do this I'd like to scale up both the image and cropping box's dimensions until the cropping box hits either the maxHeight or maxWidth of the work space.
The crop box's top, left, width and height values should maintain relative proportions and values to the scaled image.
For this, I think I need multiply them by a scale factor = (c).
Here is a sad attempt. But the scale factor is off the planet. Since I've selected about 85% of the image, the image should only increase in scale by about 15%.
I've tried various ways to get the ratio with which I need to scale the image and crop box according to the new dimensions:
const c = Math.min( croppingAreaNewWidth / currentImageWidth, croppingAreaNewHeight / currentImageHeight);
// OR
const c = Math.min( croppingAreaOldWidth / croppingAreaNewWidth, croppingAreaOldHeight / croppingAreaNewHeight );
// OR
const c = Math.min( croppingAreaNewWidth / workspaceWidth, croppingAreaNewHeight / workspaceHeight );
I know I'm way off.
I can't work which heights/widths I have to scale up against to keep everything in proportion.
What is the correct way to calculate the scale factor that will allow me to zoom in on the cropped area ?
Any tips would be appreciated.
Okay, I worked it out. I'll leave this post just in case anyone else is interested.
The ratio for zooming in the image, and resizing the cropping box turned out to be:
// Using: Math.min( maxWidth / srcWidth, maxHeight / srcHeight )
const ratio = Math.min( workspaceWidth / croppingAreaNewHeight, workspaceHeight / croppingAreaNewHeight);
I used ratio to transform the image:
const newImageScaleValue = currentImageScaleValue * ratio;
const newImageTranslateY = (-1 * (croppingAreaNewOffsetTop * ratio )) + (currentImageTranslateY * ratio);
const translateX = (-1 * (croppingAreaNewOffsetLeft * ratio )) + (currentImageTranslateX * ratio);
const newImageWidth = currentImageWidth * ratio;
const newImageHeight = currentImageHeight * ratio;
Where the workspace is the relatively position container around the cropping space.