javascript html2canvas javascript截图并上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29972949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:25:10  来源:igfitidea点击:

html2canvas javascript screenshot and upload

javascriptjquerycanvasimage-uploadinghtml2canvas

提问by maria

Would it be possible to use html2canvas (This)to take a picture of the user`s screen but also upload the image, get the upload link and send it with ajax to the webserver?

是否可以使用 html2canvas ( This )来拍摄用户屏幕的图片,但也可以上传图像,获取上传链接并将其与 ajax 一起发送到网络服务器?

if so, how can i do this?

如果是这样,我该怎么做?

回答by Oliver Barnwell

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 api对用户的屏幕进行拍照:

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):

其次使用以下函数将返回的画布图像转换为 base64 编码的 URL(默认为 png):

canvas.toDataURL(); 

Specification For canvas.toDataURL

canvas.toDataURL 的规范

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

现在构造一个请求,将 base64 编码的 url 发送到图像上传服务器(我以 Imgur 为例)。

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.

上传图像后,您可以将上传图像的 URL POST 到您的 Web 服务器。

Specification for $.post

$.post 的规范

Specification for $.ajax

$.ajax 的规范

回答by liamness

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

然后在服务端解码base64的结果放入文件

回答by Emmanuel DAWNGHIT

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

使用上面的示例,不要忘记将其添加到 base64url,否则将无法工作:

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

More info here.

更多信息在这里