0

Who's good at maths?

I have an image and a canvas like so...

enter image description here

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

MomasVII
  • 4,641
  • 5
  • 35
  • 52

1 Answers1

0

NB: Without knowing what your next move with the cropped image would be:

Consider ZOOMING the cropped image instead of calculating dimensions yourself.

For example, to double the cropped image...

crop.scale(2,2);