How to put an image to clipboard in Javascript?

时间:2017-08-30 20:33:10

标签: javascript html5 clipboarddata

How to put image to clipboard using Javascript (in handler of copy event) as if it would by done by right click on image in browser and selecting "Copy Image" from context menu.

This script shows details of clipboard content. For copied image it prints:

#top-background-flag:after {
  content: "";
  background-color: red;
  height: 2px;
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 23px;
  transform: rotate(-5.5deg);
}

So the question can be probably reformulated - how to attach a file to ForEach in Get-ChildItem -LiteralPath $Target -Directory -Recurse -Force | Where-Object { !$_.GetFiles('*','AllDirectories') } | Select-Object -Property 'FullName' | Out-GridView -PassThru -Title 'Select folders for deletion and click OK' | ForEach-Object { Remove-Item -LiteralPath $_.FullName -WhatIf } event handler function?

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" }

Not working demo using setData() method.

1 个答案:

答案 0 :(得分: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>