JS实用方法DataUrl转为File、url转base64

1,DataUrl转为File


/**
* DataUrl转为File
* @param {String} dataUrl - dataUrl地址
* @param {String} fileName - file文件名
*/
dataURLtoFile(dataUrl, fileName){
    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 File([u8arr], fileName, {type:mime});
}

2,url转base64


/**
* url转base64
* @param {String} url - url地址
*/
urlToBase64(url) {
    return new Promise ((resolve,reject) => {
        let image = new Image();
        image.onload = function() {
            let canvas = document.createElement('canvas');
            canvas.width = this.naturalWidth;
            canvas.height = this.naturalHeight;
            // 将图片插入画布并开始绘制
            canvas.getContext('2d').drawImage(image, 0, 0);
            // result
            let result = canvas.toDataURL('image/png')
            resolve(result);
        };
        // CORS 策略,会存在跨域问题https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
        image.setAttribute("crossOrigin",'Anonymous');
        image.src = url;
        // 图片加载失败的错误处理
        image.onerror = () => {
            reject(new Error('转换失败'));
        };
    });
}
//使用例子
this.urlToBase64(this.Url).then(res=>{
    console.log(res);
})

3,生成Uuid

function CreateUuid() {
    let Time = new Date().getTime();
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
    .replace(/[xy]/g, function(res) {
        let Random = (Time + Math.random() * 16) % 16 | 0;
        Time = Math.floor(Time / 16);
        return (res == 'x' ? Random : (Random & 0x3 | 0x8)).toString(16);
    });
    return "pdd"+ uuid;
};

4,获取url路径后的参数


// 不传name返回所有值,否则返回对应值
function getUrlParams(name) {
    var url = window.location.search;
    if (url.indexOf('?') == 1) { return false; }
    url = url.substr(1);
    url = url.split('&');
    var name = name || '';
    var nameres;
    // 获取全部参数及其值
    for(var i=0;i<url.length;i++) {
        var info = url[i].split('=');
        var obj = {};
        obj[info[0]] = decodeURI(info[1]);
        url[i] = obj;
    }
    // 如果传入一个参数名称,就匹配其值
    if (name) {
        for(var i=0;i<url.length;i++) {
            for (const key in url[i]) {
                if (key == name) {
                    nameres = url[i][key];
                }
            }
        }
    } else {
        nameres = url;
    }
    // 返回结果
    return nameres;
}

5,Canvas生成水印


/**
* Canvas生成水印
* @param {dom} element - dom元素
* @param {String} text - 水印文本
*/
function watermark(element, text) {
    var canvas = ''
        , ctx = ''
        , data = ''
        , fontWidth = '12.5'
        , node = document.querySelector(element)
        , width = node.clientWidth
        , height = node.clientHeight;
    canvas = document.createElement("canvas");
    canvas.width = "100";
    canvas.height = "100";
    ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, 200, 200);
    fontWidth = document.documentElement.clientWidth * 3 * 12.5 / 4000;
    ctx.font = fontWidth + "px 黑体";
    ctx.rotate(-20 * Math.PI / 180);
    ctx.fillStyle = "rgba(0,0,0, .2)";
    ctx.fillText(text, -20, 80);
    data = canvas.toDataURL("image/png", 1);
    node.style.background = 'url(' + data + ') repeat';
};
watermark("#canvas","相约1998");

6,请求本地Json


let Params = 'data/data.json';

// 方法一
var PddAjax2 = new Promise(PddAjax);
// 成功
PddAjax2.then(function(res){
    console.log(res)
})
function PddAjax(resolve , reject){
    this.Params = Params;
    $.ajax({
        type:'get',
        url:Params,
        success: function(res) {
            resolve(res);
        },
        error: function(res) {
            reject(res);
        }
    })
}

// 方式二
async function request(res){
    let request = await fetch(Params);
    let res = await request.json();
    console.log(res);
};

评论