900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 图片等比例缩放算法(计算缩放后的宽高)

图片等比例缩放算法(计算缩放后的宽高)

时间:2021-11-21 09:36:58

相关推荐

图片等比例缩放算法(计算缩放后的宽高)

让图片能够自适应父容器的宽高,并且保证图片不变形不溢出,那么就需要对图片进行等比例缩放,拿到缩放后的宽高重新赋值即可,具体算法如下:

// 分别传入图片宽高、父容器宽高const transformImgRatio = (imgWidth, imgHeight, containerWidth, containerHeight) => {let [// 用于设定图片的宽和高tempWidth,tempHeight,] = [0,0]try {imgWidth = parseFloat(imgWidth)imgHeight = parseFloat(imgHeight)containerWidth = parseFloat(containerWidth)containerHeight = parseFloat(containerHeight)} catch (error) {throw new Error('抱歉,我只接收数值类型或者可以转成数值类型的参数')}if (imgWidth > 0 && imgHeight > 0) {//原图片宽高比例 大于 指定的宽高比例,这就说明了原图片的宽度必然 > 高度if (imgWidth / imgHeight >= containerWidth / containerHeight) {if (imgWidth > containerWidth) {tempWidth = containerWidth// 按原图片的比例进行缩放tempHeight = (imgHeight * containerWidth) / imgWidth} else {// 按照图片的大小进行缩放tempWidth = imgWidthtempHeight = imgHeight}} else { // 原图片的高度必然 > 宽度if (imgHeight > containerHeight) {tempHeight = containerHeight// 按原图片的比例进行缩放tempWidth = (imgWidth * containerHeight) / imgHeight} else {// 按原图片的大小进行缩放tempWidth = imgWidthtempHeight = imgHeight}}}return { width: tempWidth, height: tempHeight }}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。