图片不变形缩小显示
1、代码示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
/*设置外框大小并将图片居中显示*/
.img-box{
width: 350px;
height: 250px;
border: 1px solid gray;
display: flex;
justify-content: center;
align-items: center;
}
.text-color {
color: red;
}
</style>
</head>
<body>
<h2 class="text-color">
原图片
</h2>
<div class="">
<img src="img/timg1.jpg"/>
</div>
<h2 class="text-color">
比例缩小后的图片
</h2>
<div class="img-box">
<div class="">
<img src="img/timg1.jpg" onload="AutoSize(this,350,250)"/>
</div>
</div>
</body>
<script type="text/javascript">
/*
*@param {string} theImg -- theImg:要放图片的img元素,onload调用函数时传参this
*@param {number} maxWidth -- maxHeight :img元素的高度,像素(图片框 最大高度)
*@param {number} maxHeight -- maxWidth:img元素的宽度,像素(图片框 最大宽度)
*@email [email protected]
* */
function AutoSize(theImg, maxWidth, maxHeight) {
/*原图片原始地址(用于获取原图片的真实宽高,当<theImg>标签指定了宽、高时不受影响)*/
var newImage = new Image();
newImage.src = theImg.src;
/*当图片比图片框小时不做任何改变 */
if(newImage.width < maxWidth && newImage.height < maxHeight) {
theImg.width = newImage.width;
theImg.height = newImage.height;
} else {
/*当原图片宽高比例大于图片框宽高比例,则以框的宽为标准缩放,反之以框的高为标准缩放*/
if((maxWidth / maxHeight) <= (newImage.width / newImage.height)) {
/*原图片宽高比例大于图片框宽高比例时*/
var widthAuto = ((maxWidth - 0.1) / maxWidth * 100).toString() + '%';
theImg.setAttribute("width", widthAuto);
theImg.height = maxWidth * (newImage.height / newImage.width);
} else {
/*原图片宽高比例小于图片框宽高比例时*/
var widthAuto = ((maxHeight * (newImage.width / newImage.height) - 0.1) / maxWidth * 100).toString() + "%";
theImg.setAttribute("width", widthAuto);
theImg.height = maxHeight;
}
}
}
</script>
</html>
2、运行结果