<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <!-- 压缩时要用到的canvas --> <canvas id="canvas" style="display:none;"></canvas> <!-- 原始图片 --> <img id="img" src="e.png" /> <!-- 压缩后的图片 --> <img id="new_image"/> <script> var maxWidth = 300; var maxHeight = 300; // 创建 canvas var c=document.getElementById("canvas"); var ctx=c.getContext("2d"); // 创建要绘制的Image对象 var img = new Image(); img.src = "e.png"; // 等待img加载完毕 img.onload = function(){ // 与backgournd-size:contain效果相同 if(img.width/img.height<maxWidth/maxHeight){ c.height = img.height; if(img.height>maxHeight){ c.height = maxHeight; } c.width = img.width/img.height*c.height; }else{ c.width = img.width; if(img.width>maxWidth){ c.width = maxWidth; } c.height = img.height/img.width*c.width; } ctx.drawImage(img,0,0,img.width,img.height,0,0,c.width,c.height); document.getElementById("new_image").src=c.toDataURL(); }; </script> </body> </html>
原文地址:http://antlove.blog.51cto.com/10057557/1741128