var c = document.createElement('canvas'), cx = c.getContext('2d'), s = document.querySelector('section'); document.querySelector('form').appendChild(c); i = null; document.querySelector( 'form' ).addEventListener( 'submit', function( ev ) { var iw = document.querySelector( '#imagew' ).value, ih = document.querySelector( '#imageh' ).value, tw = document.querySelector( '#thumbw' ).value, th = document.querySelector( '#thumbh' ).value; var i = document.createElement( 'img' ); s.innerHTML = ''; i.src = 'http://placekitten.com/g/' + iw + '/' + ih; s.appendChild( i ); i.onload = function() { var dimensions = resize( iw, ih, tw, th ); c.width = tw; c.height = th; cx.drawImage( i, dimensions.x, dimensions.y, dimensions.w, dimensions.h ); } ev.preventDefault(); },false); function resize( imagewidth, imageheight, thumbwidth, thumbheight ) { var w = 0, h = 0, x = 0, y = 0, widthratio = imagewidth / thumbwidth, heightratio = imageheight / thumbheight, maxratio = Math.max( widthratio, heightratio ); if ( maxratio > 1 ) { w = imagewidth / maxratio; h = imageheight / maxratio; } else { w = imagewidth; h = imageheight; } x = ( thumbwidth - w ) / 2; y = ( thumbheight - h ) / 2; return { w:w, h:h, x:x, y:y }; };
<form> <p><label for="imagew">Image Width: </label> <input type="number" id="imagew" value="300"> <label for="imageh">Image Height: </label> <input type="number" id="imageh" value="200"></p> <p><label for="thumbw">Thumbnail Width: </label> <input type="number" id="thumbw" value="50"> <label for="thumbh">Thumbnail Height: </label> <input type="number" id="thumbh" value="50"></p> <p><input type="submit" value="make it so!"></p> </form> <section> </section>
* { margin: 0; padding: 0; } body { padding: 20px; font-size: 15px; font-family: helvetica, arial, sans-serif; } input[type=number]{width:5em} h1 {padding-bottom: 20px} footer, section, header, aside, figure { display: block; } canvas { border: 1px solid #000; }