生成 div 的图像并另存为

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

I'd like to create an input button "Save image" that :

  1. 截取 div 的屏幕截图
  2. 要求在用户的计算机上另存为"

我发现了如何使用 html2canvas 创建潜水屏幕并在新标签中打开它,它可以完美运行:

I've found how to create a screen of a dive using html2canvas and to open it in a new tab, it works perfectly :

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

但对你来说,另存为一部分,是一个艰难的部分......我发现了一些有趣的话题,因为我是 JS(和对象)编码的新手,我有点困惑......我想我必须使用 FileSaver.js 并创建一个新的 blobhttp://eligrey.com/blog/post/saving-generated-files-在客户端/

But for thee Save as part, is a kind of the tough part... I've found interesting topics, as I'm new in JS (and object) coding, I'm a little bit confused... I think I'll have to use the FileSaver.js and to create a new blob http://eligrey.com/blog/post/saving-generated-files-on-the-client-side/

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

But I don't get how to implement the saveAs in my html2canvas, how to cast properly a new 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

Also I tried to do something with this, by extracting the base64 generated URL, but it's too complicated for me to understand everyting : http://bl.ocks.org/nolanlawson/0eac306e4dac2114c752

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

But someone give me a few tips and help me please ?

推荐答案

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

Here is the final code, if it can helps you :

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); 
}

相关文章