A crop picker often displays an image smaller than its source. If the picker reports a rectangle in displayed coordinates, passing those numbers directly to drawImage() selects the wrong part of the source. Scale the selection into intrinsic image coordinates first.
For an HTMLImageElement , drawImage() uses intrinsic dimensions. image.width can describe a displayed size, so use naturalWidth and naturalHeight when calculating the source rectangle. See MDN's drawImage notes .
Assume the entire decoded image is displayed in a 600 by 400 coordinate area. Its intrinsic dimensions are 2400 by 1600. A selection beginning at displayed point (150, 100), with displayed width 300 and height 200, maps to source point (600, 400), width 1200 and height 800.
This helper performs the scaling. The rectangle must already be relative to the displayed image content, excluding borders, padding, and any letterboxing.…