js等比缩放图片 居中

需求,给定相框大小,将所选图片等比缩放进相框居中位置 

因为要求精确度不高,在计算时取了2位小数,对结果取整


/**
 * 等比缩放图片并居中摆放
 * @param width
 *        图片宽
 * @param height
 *        图片高
 * @param pWidth
 *        父容器宽
 * @param pHeight
 *        父容器高
 */
computeImageStyle (width, height, pWidth, pHeight) {
	let imageWidth = width
	let imageHeight = height
	let marginTop = null // 图片到相框上边距离
	let marginLeft = null // 图片到相框左边距离
	let widthRation = Number(pWidth/imageWidth + '').toFixed(2)*1 // 相框与图片宽的比
	let heightRation = Number(pHeight/imageHeight + '').toFixed(2)*1 // 相框与图片高的比
	if(widthRation <= heightRation){ 
		// 按图片宽等比调整
		if(widthRation >= 1) {
			//使用原图片的宽高,并计算样式
			marginTop = Number((pHeight - imageHeight)/2  + '').toFixed(2)*1
			marginTop = (marginTop + '').split('.')[0]
			marginLeft = Number((pWidth - imageWidth)/2  + '').toFixed(2)*1
			marginLeft = (marginLeft + '').split('.')[0]
		}else{
			imageHeight = Number(imageHeight*widthRation + '').toFixed(2)*1
			imageHeight = (imageHeight + '').split('.')[0] // 取整
			imageWidth = (pWidth + '').split('.')[0]
			marginTop = Number((pHeight - imageHeight)/2  + '').toFixed(2)*1
			marginTop = (marginTop + '').split('.')[0]
		}
	}else{
		// 按图片高等比调整
		if(heightRation >= 1) {
			//使用原图片的宽高,并计算样式
			marginTop = Number((pHeight - imageHeight)/2  + '').toFixed(2)*1
			marginTop = (marginTop + '').split('.')[0]
			marginLeft = Number((pWidth - imageWidth)/2  + '').toFixed(2)*1
			marginLeft = (marginLeft + '').split('.')[0]
		}else{
			imageWidth = Number(imageWidth*heightRation + '').toFixed(2)*1
			imageWidth = (imageWidth + '').split('.')[0] // 取整
			imageHeight = (pHeight + '').split('.')[0]
			marginLeft = Number((pWidth - imageWidth)/2  + '').toFixed(2)*1
			marginLeft = (marginLeft + '').split('.')[0]
		}
	}
	return {width: imageWidth, height: imageHeight, marginTop: marginTop, marginLeft: marginLeft}
}

margin为null的不设置样式

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值