Menu

Map a displayed crop rectangle into intrinsic image coordinates
📰

Map a displayed crop rectangle into intrinsic image coordinates

DEV Community: html·David Miller·16 days ago
#h7Rm6AOC
#devto2#devto#dev#rect#height
Long article (442 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.