使用jQuery裁剪上传预览

时间:2014-11-05 23:41:59

标签: javascript jquery

我目前在用户添加图片时进行了图片预览。

js看起来像这样:

       function logoImg(input) {
        if (input.files && input.files[0]) {
          var reader = new FileReader();

          reader.onload = function (e) {
          $('#logo_img_prev')
          .attr('src', e.target.result)
          .width(210)
          .height(165);
        };

        reader.readAsDataURL(input.files[0]);
        }
      }

这非常适合显示图像。但我希望图像裁剪到那些尺寸而不是调整照片大小。我可以使用什么jquery来实现它?

1 个答案:

答案 0 :(得分:0)

CSS是你的答案。

您需要将图像设置为背景并使用background-size: cover。这会将照片缩小到可能的最小尺寸并保持比例。

使用<div>之类的元素:

<div id="logo_img_prev">
</div>

你应该是JS:

reader.onload = function (e) {
  $('#logo_img_prev')
      .css({
          'background-image': 'url(' + e.target.result + ')',
          'background-size': 'contain',
          'width': '210px',
          'height': '165px'
      });
  };