javascript - Reszing an image so it fits inside a specific size canvas and keeps aspect ratio -


i have boxes have dimensions of 340 x 170 , users uploading images need displayed these boxes; i'm not sure how go resizing them don't lose aspect ratio , fit in box.

requirements..

  • canvas should 340 x 170
  • image can't lose aspect ratio
  • if image has greater width height should wide possible 340px
  • ditto height
  • should able see whole image in canvas

normally resize largest side, won't work end larger height 170px if height close width.

what care relationship between image's aspect ratio , canvas' aspect ratio.

here's self-explanatory code (would glad add explanation if needed):

var imgratio = img.width / img.height; // image aspect ratio var canvasratio = canvas.width / canvas.height; // canvas aspect ratio  var resultimageh, resultimagew; // variables hold result of sizing algorithm  if(imgratio < canvasratio) {     resultimageh = canvas.height;     resultimagew = resultimageh * imgratio; } else {     resultimagew = canvas.width;     resultimageh = resultimagew / imgratio; } 

Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -