生成div的图像并另存为

时间:2015-11-12 09:53:56

标签: javascript base64 blob html2canvas filesaver.js

我想创建一个输入按钮“保存图像”:

  1. 拍摄div的屏幕截图
  2. 要求在用户的计算机上“另存为”
  3. 我已经找到了如何使用html2canvas创建潜水屏幕并在新标签中打开它,它完美无缺:

    function printDiv2(div)
    {
        html2canvas((div), {
            onrendered: function(canvas) {
                var img = canvas.toDataURL();
                window.open(img);
          }
        });
    }
    

    但是对于你保存为部分,是一种困难的部分...我发现了有趣的话题,因为我是JS(和对象)编码的新手,我有点困惑......我想我将不得不使用FileSaver.js并创建一个新的blob http://eligrey.com/blog/post/saving-generated-files-on-the-client-side/

    但我不知道如何在我的html2canvas中实现saveAs,如何正确地投射新的blob ......

    function printDiv2(div)
    {
        html2canvas((div), {
            onrendered: function(canvas) {
                var img = canvas.toDataURL();
                window.open(img);
    
                var blob = new Blob(img, {type: "image/jpeg"});
                var filesaver = saveAs(blob, "my image.png");
          }
        });
    }
    

    此外,我尝试通过提取base64生成的URL来做一些事情,但是对于我来说理解每一个事情太复杂了: http://bl.ocks.org/nolanlawson/0eac306e4dac2114c752

    但是有人给我一些提示并帮助我吗?

4 个答案:

答案 0 :(得分:9)

你可以这样做:

    //Creating dynamic link that automatically click
    function downloadURI(uri, name) {
        var link = document.createElement("a");
        link.download = name;
        link.href = uri;
        link.click();
        //after creating link you should delete dynamic link
        //clearDynamicLink(link); 
    }

    //Your modified code.
    function printToFile(div) {
        html2canvas(div, {
            onrendered: function (canvas) {
                var myImage = canvas.toDataURL("image/png");
                //create your own dialog with warning before saving file
                //beforeDownloadReadMessage();
                //Then download file
                downloadURI("data:" + myImage, "yourImage.png");
            }
        });
    }

答案 1 :(得分:6)

这是最终的代码,如果它可以帮助你:

function PrintDiv(div)
{
    html2canvas((div), {
        onrendered: function(canvas) {
            var myImage = canvas.toDataURL();
            downloadURI(myImage, "MaSimulation.png");
      }
    });
}

function downloadURI(uri, name) {
    var link = document.createElement("a");

    link.download = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click();   
    //after creating link you should delete dynamic link
    //clearDynamicLink(link); 
}

答案 2 :(得分:1)

你看过

吗?

http://eligrey.com/demos/FileSaver.js/

看起来它可以满足您的需求

答案 3 :(得分:1)

这对我来说很好。

function downloadURI(uri, name) {
    var link = document.createElement("a");

    link.download = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    clearDynamicLink(link); 
}

function DownloadAsImage() {
    var element = $("#table-card")[0];
    html2canvas(element).then(function (canvas) {
        var myImage = canvas.toDataURL();
        downloadURI(myImage, "cartao-virtual.png");
    });
}