javascript – 如何使用html2canvas上传截图?

使用html2canvas如何将屏幕截图保存到对象?我一直在探索演示,并看到生成屏幕截图的函数生成如下:

$(window).ready(function() {
  ('body').html2canvas();       
});

我尝试过的是

$(window).ready(function() {
  canvasRecord = $('body').html2canvas(); 
  dataURL = canvasRecord.toDataURL("image/png");
  dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
  upload(dataURL);

});

然后,我将其传递给我的upload()函数.我遇到的问题是,我无法弄清楚在html2canvas()库中制作屏幕截图的位置或者什么函数返回它.我已经尝试使用来自SO的this回答转换画布对象(虽然我不确定我需要这样做).

我刚刚问question如何将文件上传到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);
}

解决方法:

我已经从this answer修改并注释了该方法.它只发送一个具有给定名称的文件,该文件由< 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'));
}
上一篇:javascript – 如何使用jsPDF在PDF中以两页显示图像?


下一篇:html2canvas + jspdf 实现 html 转 pdf