简体   繁体   English

html2canvas javascript截图和上传

[英]html2canvas javascript screenshot and upload

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? 如果是的话,我该怎么做?

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发布到Web服务器。

Specification for $.post $ .post的规格

Specification for $.ajax $ .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 然后解码服务器端base64的结果并放入文件

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 . 更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM