djq*_*djq 9 javascript ajax upload screenshot html2canvas
使用html2canvas如何将屏幕截图保存到对象?我一直在探索演示,并看到生成屏幕截图的函数生成如下:
$(window).ready(function() {
('body').html2canvas();
});
Run Code Online (Sandbox Code Playgroud)
我尝试过的是
$(window).ready(function() {
canvasRecord = $('body').html2canvas();
dataURL = canvasRecord.toDataURL("image/png");
dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
upload(dataURL);
});
Run Code Online (Sandbox Code Playgroud)
然后,我将其传递给我的upload()
函数.我遇到的问题是,我无法弄清楚在html2canvas()
库中制作屏幕截图的位置或者什么函数返回它.我试着转换使用Canvas对象这从SO答案(虽然我不能肯定我需要做到这一点).
我只问了一个问题,关于如何上传文件到imgur,有答案(尤其是@ bebraw的)帮助我明白我需要做的.
该upload()
函数来自Imgur示例api帮助:
function upload(file) {
// file is from a <input> tag or from Drag'n Drop
// Is the file an image?
if (!file || !file.type.match(/image.*/)) return;
// It is!
// Let's build a FormData object
var fd = new FormData();
fd.append("image", file); // Append the file
fd.append("key", "mykey"); // Get your own key: http://api.imgur.com/
// Create the XHR (Cross-Domain XHR FTW!!!)
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://api.imgur.com/2/upload.json"); // Boooom!
xhr.onload = function() {
// Big win!
// The URL of the image is:
JSON.parse(xhr.responseText).upload.links.imgur_page;
}
// Ok, I don't handle the errors. An exercice for the reader.
// And now, we send the formdata
xhr.send(fd);
}
Run Code Online (Sandbox Code Playgroud)
我已经从这个答案中修改并注释了该方法.它只发送一个具有给定名称的文件,该文件由一个<canvas>
元素组成.
if (!('sendAsBinary' in XMLHttpRequest.prototype)) {
XMLHttpRequest.prototype.sendAsBinary = function(string) {
var bytes = Array.prototype.map.call(string, function(c) {
return c.charCodeAt(0) & 0xff;
});
this.send(new Uint8Array(bytes).buffer);
};
}
/*
* @description Uploads a file via multipart/form-data, via a Canvas elt
* @param url String: Url to post the data
* @param name String: name of form element
* @param fn String: Name of file
* @param canvas HTMLCanvasElement: The canvas element.
* @param type String: Content-Type, eg image/png
***/
function postCanvasToURL(url, name, fn, canvas, type) {
var data = canvas.toDataURL(type);
data = data.replace('data:' + type + ';base64,', '');
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
var boundary = 'ohaiimaboundary';
xhr.setRequestHeader(
'Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.sendAsBinary([
'--' + boundary,
'Content-Disposition: form-data; name="' + name + '"; filename="' + fn + '"',
'Content-Type: ' + type,
'',
atob(data),
'--' + boundary + '--'
].join('\r\n'));
}
Run Code Online (Sandbox Code Playgroud)