本文主要是介绍复制图片到剪切板,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
复制图片待剪切板
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>js复制图片-文字</title>
</head>
<body><div><img id="hidImag" src="https://static.cnodejs.org/FtG0YVgQ6iginiLpf9W4_ShjiLfU"/>
</div>
<input id="copy" type="button" style="cursor: pointer;" value="复制图片到剪切板">
<script type="text/javascript">let img = document.getElementById('hidImag')/**** @param url 图片路径* @param ext 图片格式* @param callback 结果回调*/function getUrlBase64(url, ext, callback) {var canvas = document.createElement("canvas"); //创建canvas DOM元素var ctx = canvas.getContext("2d");var img = new Image;img.crossOrigin = 'Anonymous';img.src = url;img.onload = function () {canvas.height = 100; //指定画板的高度,自定义canvas.width = 100; //指定画板的宽度,自定义ctx.drawImage(img, 0, 0, 100, 100); //参数可自定义var dataURL = canvas.toDataURL("image/" + ext);callback.call(this, dataURL); //回掉函数获取Base64编码canvas = null;};}let str1 = ''copy.onclick = function () {try {const base64Data = str1if (document.body.createControlRange) { //IE 11 需要有个img标签var controlRange;var imgs = document.getElementById('hidImag');imgs.onload = function () {controlRange = document.body.createControlRange();imgs.contentEditable = 'true';controlRange.addElement(imgs);try {var successful = controlRange.execCommand('copy');var msg = successful ? 'successful' : 'unsuccessful';console.log('Copying text command was ' + msg);} catch (err) {console.log(err);}}imgs.src = 'data:image/png;base64,' + base64Data;} else { //chromeconst blobInput = convertBase64ToBlob(base64Data, 'image/png');const clipboardItemInput = new ClipboardItem({'image/png': blobInput});navigator.clipboard.write([clipboardItemInput]);console.log(blobInput, 'success', clipboardItemInput);}} catch (e) {console.log(e);}}function convertBase64ToBlob(base64, type) {var bytes = window.atob(base64);var ab = new ArrayBuffer(bytes.length);var ia = new Uint8Array(ab);for (var i = 0; i < bytes.length; i++) {ia[i] = bytes.charCodeAt(i);}return new Blob([ab], {type: type});}getUrlBase64('https://static.cnodejs.org/FtG0YVgQ6iginiLpf9W4_ShjiLfU' , 'png', (data)=>{str1 = data.split('base64,')[1]})
</script>
</body>
</html>
这篇关于复制图片到剪切板的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!