Menu

Calculate drawImage crops from the source image dimensions
📰

Calculate drawImage crops from the source image dimensions

DEV Community: html·David Miller·4 days ago
#w2ntRGfS
#devto2#devto#dev#side#dimensions
Reading 0:00
15s threshold

A crop rectangle passed to drawImage() belongs to the source image. Calculate it from the intrinsic image dimensions, including when CSS makes the preview smaller.

Suppose a decoded image has intrinsic dimensions of 1600 by 1200, and its preview is 400 by 300. A source crop 200 units wide covers one eighth of the image width. A 200-unit selection in the preview covers half its width.

Use naturalWidth and naturalHeight when calculating a centered square for an HTMLImageElement :

function drawSquare ( ctx , img , outputSize = 256 ) { const side = Math . min ( img . naturalWidth , img . naturalHeight ); if ( side <= 0 ) throw new Error ( " Image has no usable dimensions " ); const sx = ( img . naturalWidth - side ) / 2 ; const sy = ( img . naturalHeight - side ) / 2 ; ctx . drawImage ( img , sx , sy , side , side , 0 , 0 , outputSize , outputSize ); }

Enter fullscreen mode

Exit fullscreen mode

Decode the image before calling this function.…

Continue reading — create a free account

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