@@ -219,10 +219,33 @@ const TcgCardGeneratorPage = () => {
219219 if ( image ) {
220220 const img = new Image ( ) ;
221221 img . src = image ;
222+
223+ const drawImageCover = ( img ) => {
224+ const srcRatio = img . width / img . height ;
225+ const destRatio = imgW / imgH ;
226+ let sx , sy , sWidth , sHeight ;
227+
228+ if ( srcRatio > destRatio ) {
229+ // Image is wider than destination: crop width
230+ sHeight = img . height ;
231+ sWidth = img . height * destRatio ;
232+ sx = ( img . width - sWidth ) / 2 ;
233+ sy = 0 ;
234+ } else {
235+ // Image is taller than destination: crop height
236+ sWidth = img . width ;
237+ sHeight = img . width / destRatio ;
238+ sx = 0 ;
239+ sy = ( img . height - sHeight ) / 2 ;
240+ }
241+
242+ ctx . drawImage ( img , sx , sy , sWidth , sHeight , imgX , imgY , imgW , imgH ) ;
243+ } ;
244+
222245 if ( img . complete ) {
223- ctx . drawImage ( img , imgX , imgY , imgW , imgH ) ;
246+ drawImageCover ( img ) ;
224247 } else {
225- img . onload = ( ) => ctx . drawImage ( img , imgX , imgY , imgW , imgH ) ;
248+ img . onload = ( ) => drawImageCover ( img ) ;
226249 }
227250 } else {
228251 ctx . fillStyle = '#222' ;
@@ -343,7 +366,11 @@ const TcgCardGeneratorPage = () => {
343366 if ( file ) {
344367 const reader = new FileReader ( ) ;
345368 reader . onload = ( event ) => {
346- setImage ( event . target . result ) ;
369+ const img = new Image ( ) ;
370+ img . onload = ( ) => {
371+ setImage ( event . target . result ) ;
372+ } ;
373+ img . src = event . target . result ;
347374 } ;
348375 reader . readAsDataURL ( file ) ;
349376 }
0 commit comments