html - how to set auto width of image in javascript -
i have code in uploading image displays image resized one.
<!doctype html> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="content-type" /> <title>image preview example</title> </head> <body onload="loadimagefile();"> <form name="uploadform"> <table> <tbody> <tr> <td><img id="originalimg"/></td> <td><img id="uploadpreview"/></td> <td><input id="uploadimage" type="file" name="myphoto" onchange="loadimagefile();" /></td> </tr> </tbody> </table> </form> </body> <script type="text/javascript"> ofreader = new filereader(), rfilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i; ofreader.onload = function (ofrevent) { var img=new image(); img.onload=function(){ document.getelementbyid("originalimg").src=img.src; var canvas=document.createelement("canvas"); var ctx=canvas.getcontext("2d"); canvas.width=img.width/2; canvas.height= img.height/2; ctx.drawimage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height); document.getelementbyid("uploadpreview").src = canvas.todataurl(); alert(canvas.todataurl()); } img.src=ofrevent.target.result; }; function loadimagefile() { if (document.getelementbyid("uploadimage").files.length === 0) { return; } var ofile = document.getelementbyid("uploadimage").files[0]; if (!rfilter.test(ofile.type)) { alert("you must select valid image file!"); return; } ofreader.readasdataurl(ofile); } </script> </html> now in line :
canvas.width=img.width/2; canvas.height= img.height/2; sets canvas/resized image img width divide 2 half of value.
my question how can set static value of width , height auto resized value?
i tried didn't work.
canvas.width=500; canvas.height='auto';
you have calculate ratio of actual image, can use easy calculation :
var ratio = img.height/img.width; canvas.width = wantedwidth; canvas.height = ratio*wantedwidth; document.queryselector('button').addeventlistener('click', function() { var wantedwidth = +wwidth.value; img.onload = function() { var ratio = img.height/img.width; canvas.width = wantedwidth; canvas.height = ratio*wantedwidth; canvas.getcontext('2d').drawimage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height); } img.src = 'http://lorempixel.com/' + owidth.value + '/' + oheight.value; }, false); original width : <input type="number" id="owidth" value="200" /><br> original height : <input type="number" id="oheight" value="400" /><br> wanted width : <input type="number" id="wwidth" value="300" /><br> <button>set it</button><br> <canvas id="canvas"></canvas> <img id="img" src="" />
Comments
Post a Comment