javascript – 将图像复制到剪贴板

看起来,您不能(还)以编程方式从JavaScript Web应用程序将图像复制到剪贴板?

我试图在剪贴板中复制文本,但它确实有效.

现在我想复制一个图像,然后按ctrl v粘贴到Word或Excel或Paint.

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

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

解决方法:

我搜索了互联网,无法找到解决方案,所以我继续进行实验.在所有浏览器中成功运行:

我用于测试的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

上一篇:使用Java将文本复制到剪贴板


下一篇:复制