/** * 计算图片缩放比例 使图片不变形 * @param {*} boxEle 图片外围盒子元素 * @param {*} src 当前图片src * @param {*} callback 回调方法 */ export const getImgSize = (boxEle, src, callback) => { let box_W = boxEle.clientWidth let box_H = boxEle.clientHeight var nImg = new Image(); nImg.onload = function() { var img_w = nImg.width, img_h = nImg.height; // 比例 let b1 = img_w/box_W let b2 = img_h/box_H if(b1 <= 1 && b2 <= 1){ img_w = img_w img_h = img_h }else if(b1 <= 1 && b2 > 1){ img_w = img_w/b2 img_h = '100%' }else if(b1 > 1 && b2 < 1){ img_w = '100%' img_h = img_h/b1 }else if(b1 > 1 && b2 > 1){ let b = b1 > b2 ? b1 : b2 // 取比例大的 img_w = img_w / b img_h = img_h / b } callback({w: img_w, h: img_h}); } nImg.src = src; }