vue 抽离js

1、项目结构
vue 抽离js_第1张图片
idcard.js

export default{
    install(Vue) {
        Vue.prototype.$scaleimg = function (img) {
            let height=img.currentTarget.height;
            let width=img.currentTarget.width;
            let base64data='';
            let can=document.createElement("canvas");
            can.height=height;
            can.width=width;
            let casimg=can.getContext('2d');
            casimg.clearRect(0, 0,width,height);
            casimg.drawImage(img.currentTarget,0,0,width,height);
            base64data=can.toDataURL('image/*');
            let size=Math.round( this.$dataURLtoBlob(base64data).size/1024);
            let maxsize=800;
            if(size>maxsize){
                if(size<1300){
                    img.currentTarget.height=Math.round(height*(3/4));
                    img.currentTarget.width=Math.round(width*(3/4));
                    return this.$scaleimg(img);
                } else if(size<1800){
                    img.currentTarget.height=Math.round(height*(2/3));
                    img.currentTarget.width=Math.round(width*(2/3));
                    return this.$scaleimg(img);
                } else{
                    img.currentTarget.height=Math.round(height/2);
                    img.currentTarget.width=Math.round(width/2);
                    return this.$scaleimg(img);
                }
            }
            else{
                base64data = base64data.split(",")[1];
                return base64data;
            }
        }
        Vue.prototype.$dataURLtoBlob = function (dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        }
    }
}

2、在main.js引入
vue 抽离js_第2张图片
3、使用

this.$scaleimg(e)

你可能感兴趣的:(vue,前端)