2015-10-16 184 views
9

表面上看,您不能以编程方式将图像从JavaScript Web应用程序复制到剪贴板?将图像复制到剪贴板

我试图复制剪贴板中的文本,它的工作。

现在我想复制的图像后,我按CTRL +v粘贴到Word或Excel或画图。

$(function() { 
    $("#btnSave").click(function() { 
     html2canvas($("#container1"), { 
      onrendered: function(canvas) { 
       theCanvas = canvas; 

       document.body.appendChild(canvas); 
       Canvas2Image.saveAsPNG(canvas); 
       $("#img-out").append(canvas); 
      } 
     }); 
    }); 
}); 

回答

0

看看这个指南,复制和粘贴的JavaScript:https://www.lucidchart.com/techblog/2014/12/02/definitive-guide-copying-pasting-javascript/

根据此目的,Chrome,Safari浏览器和Firefox以及纯文本都支持复制的图像,而IE只允许复制文本。上面链接的页面描述了该服务如何使用扩展将此功能添加到上下文菜单,但似乎有几个浏览器支持对图像进行编程复制。

+1

没有支持将图像数据复制到剪贴板中。 https://bugs.chromium.org/p/chromium/issues/detail?id=150835。看起来它已经开放了大约4年。 – notsiddhartha

11

剪贴板API规范。

我使用测试的HTML是:

<div class="copyable"> 
    <img src="images/sherlock.jpg" alt="Copy Image to Clipboard via Javascript."/> 
</div> 
<div class="copyable"> 
    <img src="images/stark.jpg" alt="Copy Image to Clipboard via Javascript."/> 
</div> 

中的JavaScript/jQuery代码看起来是这样的:

<script> 
     //Cross-browser function to select content 
     function SelectText(element) { 
      var doc = document; 
      if (doc.body.createTextRange) { 
       var range = document.body.createTextRange(); 
       range.moveToElementText(element); 
       range.select(); 
      } else if (window.getSelection) { 
       var selection = window.getSelection(); 
       var range = document.createRange(); 
       range.selectNodeContents(element); 
       selection.removeAllRanges(); 
       selection.addRange(range); 
      } 
     } 
     $(".copyable").click(function (e) { 
      //Make the container Div contenteditable 
      $(this).attr("contenteditable", true); 
      //Select the image 
      SelectText($(this).get(0)); 
      //Execute copy Command 
      //Note: This will ONLY work directly inside a click listenner 
      document.execCommand('copy'); 
      //Unselect the content 
      window.getSelection().removeAllRanges(); 
      //Make the container Div uneditable again 
      $(this).removeAttr("contenteditable"); 
      //Success!! 
      alert("image copied!"); 
     }); 
</script> 

上传GitHub上,以及在所有浏览器成功运行: https://github.com/owaisafaq/copier-js

+2

不适用于我的Chrome 55 – benkol

+2

这不会将类型为'file'的'DataTransferItem'添加到'ClipboardEvent',而是从Web浏览器图像上下文菜单中纯粹的“复制图像”。基本上这个代码将图像作为HTML内容而不是纯图像传递。 – czerny

+1

在Firefox 56,Chrome 61和Opera 48中不起作用。您使用了哪种浏览器? –