html2canvas javascript screenshot and upload

耗尽温柔 提交于 2019-12-03 03:26:54

Yes it is certainly possible to do such a thing.

Firstly use the html2canvas api to take a picture of the user's screen:

html2canvas(document.body).then(function(canvas) {
});

Secondly use the following function to convert the returned canvas image into a base64 encoded URL (defaults to png):

canvas.toDataURL(); 

Specification For canvas.toDataURL

Now construct a request to send your base64 encoded url to an image uploading server (I'm using Imgur as an example).

html2canvas(document.body).then(function(canvas) {
    var dataURL = canvas.toDataURL();
    $.ajax({
        url: 'https://api.imgur.com/3/image',
        type: 'post',
        headers: {
            Authorization: 'yourauthcode'
        },
        data: {
            image: dataURL
        },
        dataType: 'json',
        success: function(response) {
            if(response.success) {
               // Post the imgur url to your server.
               $.post("yourlinkuploadserver", response.data.link);
            }
        }
    });
});

After the image has been uploaded you can POST the URL of the uploaded image to your web server.

Specification for $.post

Specification for $.ajax

This isn't tested, but should work

function screenshot() {
    html2canvas(document.body).then(function(canvas) {
        // post using your favourite xhr polyfill, e.g. jQuery's
        $.post('http://urlgoeshere.com', canvas.toDataURL('image/png'));
    });
}

Then decode the result from base64 on the server side and put in a file

Emmanuel DAWNGHIT

Using the example above, don't forget to add this to the base64url, otherwise it won't work :

var dataURL = canvas.toDataURL().replace(/.*,/, '');

More info here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!