h5压缩图片 亲测有效

1. 在utils/base.js方法里面定义

export function	translate(imgSrc, scale, type , callback) {
					var img = new Image();
					img.src = imgSrc;
					img.onload = function() {
						var that = this;
						var h = that.height; // 默认按比例压缩
						var w = that.width;
						var canvas = document.createElement('canvas');
						var ctx = canvas.getContext('2d');
						var width = document.createAttribute("width");
						width.nodeValue = w/2;
						var height = document.createAttribute("height");
						height.nodeValue = h/2;
						canvas.setAttributeNode(width);
						canvas.setAttributeNode(height);
						ctx.drawImage(that, 0, 0, w/2,h/2);
						var base64 = canvas.toDataURL('image/jpeg', scale);//压缩比例
						canvas = null;
						callback(base64);
					}
				
			}

2. 在页面引用

 import { translate } from '@/utils/base.js';

3. 在方法里面获取在使用

translate(res.tempFilePaths[0], 0.7, '', imgUrl => {
        //压缩后返回的图片imgUrl
})

版权声明:本文为zhengyuantoo原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。