js获取图片原始比例并根据比例显示宽高

由于每个图片上传的时候比例大小都不一样,如果要在移动端展示,统一宽高效果会非常差。所以我们可以获取图片的原始宽高,然后以移动的比例展示,效果会非常好。以下就是实现方法:

 //获取图片原始宽高
getNaturalImgSize: function(img, callback) {
                /**
		 *img元素
		 *callback 回调函数
		 **/
		var nWidth, nHeight;
		if(img.naturalWidth) { // 现代浏览器
			nWidth = img.naturalWidth;
			nHeight = img.naturalHeight;
			callback({
				w: nWidth,
				h: nHeight
			});
		} else { // IE6/7/8
			var imgae = new Image()
			image.src = img.src;
			image.onload = function() {
				callback({
					w: image.width,
					h: image.height
				});
			}
		}

	},
 //打开图片预览			
 bigImgShow: function(url) {
		/**
		*url 当前点击的图片地址
		**/		
		this.bigImgSrc = url;
		this.maskBtn = true;
		this.$nextTick(function() {
			var img = document.getElementById('bigImg');
			var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
			this.getNaturalImgSize(img, function(k) {
				//图片高度按比例换算
				var imgHeight = k.h * clientWidth / k.w;
				img.style.height = imgHeight + 'px';
				img.style.width = clientWidth + 'px';

			})

		}),

	};

效果如下(宽100%,高是根据比例换算的):

js获取图片原始比例并根据比例显示宽高_第1张图片


你可能感兴趣的:(vue移动端)