如何在 javascript 中设置图像的自动宽度

how to set auto width of image in javascript

我在上传图片时使用了这段代码,然后显示调整后的图片。

<!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 a valid image file!"); return; }
  oFReader.readAsDataURL(oFile);
}
</script>
</html>

现在在这一行:

canvas.width=img.width/2;
canvas.height= img.height/2;

设置img宽度除以2的canvas/resized图像得到一半的值。

我的问题是,如何使用 width 的静态值设置它,而 height 将获得 auto 调整后的值?

我这样试过,但没用。

canvas.width=500;
canvas.height='auto';

您只需计算实际图像的比例,然后您可以使用一些简单的计算方法,例如:

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="" />