Who's good at maths?
I have an image and a canvas like so...
The Canvas at the bottom is roughly 10 times larger than the cropping box above but we are scaling up the cropped area.
I have worked out how to get the width of the cropped area to always be 100% and here is the code...
const canvas = document.createElement('canvas')
const scaleX = image.naturalWidth / image.width
const scaleY = image.naturalHeight / image.height
const ctx = canvas.getContext('2d')
const xCropScale = crop.width / image.width
canvas.width = crop.width * scaleX + image.naturalWidth * (1 - xCropScale)
canvas.height = crop.height * scaleY
ctx.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width * scaleX + image.naturalWidth * (1 - xCropScale),
crop.height * scaleY
)
The issue I am having is getting the height to scale accoring to what we have cropped AND the increase in size of the cropped area. As you can see the screenshot is correct along the X axis but the Y axis needs to scale to not make the image warped.
image.naturalWidth is my uploaded image width (Also the bottom image width) at 1000's of pixels and the image.width is the top image width of around 200px.
Thanks