美文网首页
canvas实现下载

canvas实现下载

作者: 银角大王__ | 来源:发表于2020-10-23 16:10 被阅读0次
    <!DOCTYPE html>
    <html>
    <head> 
        <meta charset="utf-8"> 
        <title>canvas实现下载</title> 
    </head>
    
    <body>
        <canvas id="myCanvas" width="200" height="100">
            您的浏览器不支持 HTML5 canvas 标签。</canvas>
        <script>
    
            var c = document.getElementById("myCanvas");
            var ctx = c.getContext("2d");
            ctx.moveTo(0, 0);
            ctx.lineTo(200, 100);
            ctx.stroke();
            var image = c.toDataURL("image/png");
    
            console.log(image)   /* base64 */
    
            // document.write('<img src="'+image+'" />');
            
         /* base64转blob对象 */
            function dataURItoBlob(code) {
                var parts = code.split(';base64,');
                var contentType = parts[0].split(':')[1];
                var raw = window.atob(parts[1]);
                var rawLength = raw.length;
                var uInt8Array = new Uint8Array(rawLength);
                for (var i = 0; i < rawLength; ++i) {
                    uInt8Array[i] = raw.charCodeAt(i);
                }
                return new Blob([uInt8Array], { type: contentType });
            }
    
            function downloadFile(fileName, content) {
                var aLink = document.createElement('a');
                // var blob = new Blob([content]);
                var blob = dataURItoBlob(content);
                var evt = document.createEvent("MouseEvents");
                evt.initEvent("click", false, false);//initEvent 不加后两个参数在FF下会报错
                aLink.download = fileName;
                aLink.href = URL.createObjectURL(blob);
                aLink.dispatchEvent(evt);
            }
            downloadFile('aaa.png', image);
        </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:canvas实现下载

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