3 个回答

看题主标题,应该有两点需求:

  1. canvas 保存图片

  2. 下载到本地

针对canvas保存图片,bf 童鞋给出了代码了

下载到本地的话,参考这个http://www.alloyteam.com/2014/01/use-js-file-download/

前段时间也捣鼓了一下,列一下我当时的代码片段:

            function base64Img2Blob(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 = base64Img2Blob(content); //new Blob([content]);
              
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent("click", false, false);//initEvent 不加后两个参数在FF下会报错
                aLink.download = fileName;
                aLink.href = URL.createObjectURL(blob);
         
                aLink.dispatchEvent(evt);
            }           
downloadFile('ship.png', canvas.toDataURL("image/png"));

亲测可用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <canvas id="canvas"></canvas>
</body>
<script>


//图片导出为 png 格式
var type = 'png';
var imgData = canvas.toDataURL(type);

/**
 * 获取mimeType
 * @param  {String} type the old mime-type
 * @return the new mime-type
*/
var _fixType = function(type) {
   type = type.toLowerCase().replace(/jpg/i, 'jpeg');
   var r = type.match(/png|jpeg|bmp|gif/)[0];
   return 'image/' + r;
}; 

// 加工image data,替换mime type
imgData = imgData.replace(_fixType(type),'image/octet-stream');

/**
 * 在本地进行文件保存
 * @param  {String} data     要保存到本地的图片数据
 * @param  {String} filename 文件名
 */
var saveFile = function(data, filename){
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = data;
    save_link.download = filename;

    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
};

// 下载后的文件名
var filename = '二维码 .' + type;
// download
saveFile(imgData,filename);



</script>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏