Mar*_*ark 5 javascript css aspect-ratio image-resizing
这似乎是之前有人问过的问题,但我找不到重复的东西,所以......
我希望图像的最小尺寸在保持纵横比的同时最大缩放 200。所以:
显然,如果它可以用 css 来完成,那么它比 javascript 更受欢迎。
是的,你需要 JS:
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
};
}
Run Code Online (Sandbox Code Playgroud)
// 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
Run Code Online (Sandbox Code Playgroud)