这似乎是以前会被问到的问题,但我找不到重复的问题,所以...
我想要将图像的最小尺寸缩放到最大200,同时保持纵横比。 所以:
- 600x400像素的图像最小尺寸为400,应该为200,因此按0.5缩放:新图像将为300x200
- 同样,400x800将变为200x400
- 100x300的最小尺寸已经小于200,因此它将保持100x300。
显然,如果可以使用CSS完成,则优先使用CSS而不是JavaScript。
这似乎是以前会被问到的问题,但我找不到重复的问题,所以...
我想要将图像的最小尺寸缩放到最大200,同时保持纵横比。 所以:
显然,如果可以使用CSS完成,则优先使用CSS而不是JavaScript。
是的,你需要使用JavaScript:
function scale(W, H, max) {
var min = Math.min(W, H), // Get the smallest size
nr = min>max, // NeededResize (Boolean)
rat = Math.min(max/W, max/H);// Ratio
return {
W: nr?W*rat:W, // if NeededResize do W*rat, else just use the image W
H: nr?H*rat:H
};
}
// Use like: scale(imageWidth, imageHeight, maxSizeToRespect);
var resize = scale(this.width, this.height, 200);
// Where from now on
resize.W // is the returned width scale
resize.H // is the returned height scale