2015-10-16 207 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中不起作用。您使用了哪種瀏覽器? –