js按比例缩放图片并显示图片的一部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
$(document).ready(function(){  
//取得图片外层div的宽度
var boxwidth = $(‘.media-object’).parent().width();
var boxheight = boxwidth*9/16;
var imgarray = $(‘.media-object’);
for(var i=0;i<imgarray.length;i++){
//获取图片原始长、宽
var width = imgarray[i].width ;
var height = imgarray[i].height;
//判断图片长宽比例
if( width*9/16 > boxheight ){
//使用宽度按16:9的比例缩放后高度不够,转而使用高度
//此时图片高度应该设为div高 boxheight
var imgheight = boxheight;
$(imgarray[i]).css(‘height’,imgheight);
//此高度下等比例的图片宽度为 imgwidth
var imgwidth = imgheight*width/height;
$(imgarray[i]).css(‘width’,imgwidth);
//计算此时图片宽度与div宽度的差值
var difference = imgwidth-boxwidth;
//计算图片应该裁剪的位置
var stratX = difference/2;
var startY = 0;
var endX = imgwidth – difference/2;
var endY = imgheight;
//使用css clip:rect(top, right, bottom, left)属性裁剪
$(imgarray[i]).css(‘clip’,’rect(‘+stratX+’px ‘+endX+’px ‘+endY+’px ‘+startY+’px)’);
}else{
//使用宽度按照16:9缩放,多余的高度去除
//此时图片宽度应该设为div宽 boxwidth
var imgwidth = boxwidth;
$(imgarray[i]).css(‘width’,imgwidth);
//此宽度下等比例的图片高度为 imgheight
var imgheight = imgwidth*height/width;
$(imgarray[i]).css(‘height’,imgheight);
//计算此时图片高度与div高度的差值
var difference = imgheight-boxheight;
//计算图片应该裁剪的位置
var stratX = 0;
var startY = difference/2;
var endX = imgwidth;
var endY = imgheight – difference/2;
//使用css clip:rect(top, right, bottom, left)属性裁剪
$(imgarray[i]).css(‘clip’,’rect(‘+stratX+’px ‘+endX+’px ‘+endY+’px ‘+startY+’px)’);
}
}
});
Author

Ludis

Posted on

2015-11-25

Updated on

2016-07-22

Licensed under

Comments