2017-08-30 23 views
2

ブラウザで画像を右クリックし、コンテキストメニューから「画像をコピー」を選択することで、Javascript(copyイベントのハンドラ内)を使用して画像をクリップボードに入れる方法。Javascriptで画像をクリップボードに入れる方法は?

このscriptは、クリップボードの内容の詳細を示します。それは印刷し、コピー画像の場合: - copyイベントハンドラ関数にclipboardDataにファイルを添付する方法

DataTransfer { dropEffect: "none", effectAllowed: "uninitialized", items: DataTransferItemList[2], types: Array[2], files: FileList[1], mozItemCount: 1, mozCursor: "auto", mozUserCancelled: false, mozSourceNode: null } 
DataTransferItem { kind: "string", type: "text/html" } 
DataTransferItem { kind: "file", type: "image/png" } 
Array [ "text/html", "Files" ] 
File { name: "image.png", lastModified: 1504122845696, lastModifiedDate: Date 2017-08-30T19:54:05.696Z, webkitRelativePath: "", size: 385273, type: "image/png" } 

そこで問題は、おそらく再公式化することができますか?

setData()方法を使用して demoを働いていない
document.addEventListener('copy', (event) => { 
    // event.clipboardData.? 
    // maybe event.clipboardData.setData(?) 
}) 

+0

あなたは検索しましたか? https://stackoverflow.com/questions/33175909/copy-image-to-clipboard – epascarello

+0

画像を右クリックすると、既にクリップボードにあるコンテキストメニューから「画像をコピー」をクリックすると表示されます。 –

+0

@ koushik-chatterjeeはい。そして私はそのような振る舞いをプログラム的にシミュレートしたいと思います。 – czerny

答えて

1

//get reference to the div 
 
var div = document.getElementById('someDiv'); 
 

 
//attach a paste event 
 
div.addEventListener('paste', function(ev){ 
 
    var imgFile = null; 
 
    var idx; 
 
    var items = ev.clipboardData.items; 
 
    for(idx=0;idx<items.length;idx++) { 
 
     //check if any content is file 
 
     if(items[idx].kind==="file") { 
 
      //take that file to imgFile 
 
      imgFile = items[idx].getAsFile(); 
 
      break; 
 
     } 
 
    } 
 
    if(imgFile==null) {return;} 
 
    
 
    //create a File reader 
 
    var reader = new FileReader(); 
 
    reader.onload = function() { 
 
     //create an img DOM object 
 
     var img = new Image(); 
 
     //reader.result is nothing but the Base64 representation 
 
     img.src = reader.result; 
 
     
 
     //operate the DOM, clear the div and append the img 
 
     div.innerHTML = ''; 
 
     div.appendChild(img); 
 
    } 
 
    //read that file using the reader 
 
    reader.readAsDataURL(imgFile); 
 
});
<div id="someDiv" style="min-width: 200px;min-height: 200px; border: 1px solid red"> 
 
Paste an image here (using Ctrl + V) 
 

 
</div>

+0

問題は、クリップボードへの画像の書き込みと 'copy'イベントの処理についてでした。この応答はクリップボードからの「ペースト」イベントと読書イメージに関するものです。 – czerny

+0

あなたはそれを扱う必要はありません。あなたが扱う必要があるのは、それをどこかに貼り付けるための貼り付けイベントです。 –

+0

おっと、 'copy image'のアクションをプログラム的に呼び出すようです –

関連する問題