Copy image to clipboard

Seemingly, you can't (yet) programmatically copy an image to the clipboard from a JavaScript web app?

I have tried to copy a text in clipboard , and it's worked.

Now I would like to copy an image and after I press ctrl+v to paste into Word or Excel or Paint.

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

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

Solution 1:

This worked across all browsers (as of 2016). I have uploaded on GitHub as well: https://github.com/owaisafaq/copier-js

//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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="copyable">
  <img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>

<div class="copyable">
  <img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>

Solution 2:

For those still looking, the ClipboardAPI now works with png images.

try {
    navigator.clipboard.write([
        new ClipboardItem({
            'image/png': pngImageBlob
        })
    ]);
} catch (error) {
    console.error(error);
}

Solution 3:

So, i created the perfect solution with 1 liner-kinda solution to convert something with html2canvas to a canvas and then produce the image of it and then save it to clipboard as png. For example,

HTML:
<div id="copyToImage">Hello World!</div>

JavaScript:

$("#copyToImage").click(function() {
    html2canvas(document.querySelector("#copyToImage")).then(canvas => canvas.toBlob(blob => navigator.clipboard.write([new ClipboardItem({'image/png': blob})])));
});