美文网首页
javascript canvas转图片下载

javascript canvas转图片下载

作者: 为了记笔记注册的账号 | 来源:发表于2019-03-19 14:55 被阅读0次

    1. 将canvas转为base64格式。

    2. 将base64转为blob格式

    downloadImg(){
            let echartsImg = $('#chart').find('canvas')[0];
            let img = echartsImg.toDataURL("image/jpeg");
            //下载
            this.downloadFile('img',img)
          },
          //base64转blob
          base64ToBlob(code) {
            let parts = code.split(';base64,');
            let contentType = parts[0].split(':')[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;
    
            let uInt8Array = new Uint8Array(rawLength);
    
            for (let i = 0; i < rawLength; ++i) {
              uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], {type: contentType});
          },
    
          //下载
          downloadFile(fileName, content) {
            let aLink = document.createElement('a');
            let blob = this.base64ToBlob(content); //new Blob([content]);
    
            let evt = document.createEvent("HTMLEvents");
            evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
            aLink.download = fileName;
            aLink.href = URL.createObjectURL(blob);
    
            aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
          },
    

    相关文章

      网友评论

          本文标题:javascript canvas转图片下载

          本文链接:https://www.haomeiwen.com/subject/cvggmqtx.html