Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - Generate an image of a div and Save as

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

  1. take a screen shot of a div
  2. ask to "Save as" on the user's computer

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

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/

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do this approach:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...