复制图片待剪切板
<!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')
function getUrlBase64(url, ext, callback) {
var canvas = document.createElement("canvas");
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);
canvas = null;
};
}
let str1 = ''
copy.onclick = function () {
try {
const base64Data = str1
if (document.body.createControlRange) {
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 {
const 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>