Vue 前端等比例图片压缩

前端压缩图片的方式是利用canvas进行压缩 代码如下

 maximg='xxx' 最长边的值
getBase64(url, callback) {
            let _that = this
            var Img = new Image(),
                dataURL = '';
            Img.src = url + "?v=" + Math.random();
            Img.setAttribute("crossOrigin", 'Anonymous')
            Img.onload = function () {
                var canvas = document.createElement("canvas"),
                    width = Img.width,
                    height = Img.height;
                if (Math.max(width, height) > _that.maximg) {
                    if (width > height) {
                        canvas.width = _that.maximg;
                        canvas.height = _that.maximg * height / width
                    } else {
                        canvas.height = _that.maximg
                        canvas.width = _that.maximg * width / height
                    }
                } else {
                    canvas.width = width;
                    canvas.height = height;

                }

                canvas.getContext("2d").drawImage(Img, 0, 0, canvas.width, canvas.height);
                dataURL = canvas.toDataURL('image/jpeg');
                callback ? callback(dataURL) : null;
            };
        },
    this.toBase64('服务器资源url’);//返回的值是base64

你可能感兴趣的:(前端,vue.js,状态模式)