介绍
需要https的支持,可将Base64或URL图片复制到黏贴版中!
/**
* 复制图片,接受 data: URI 和 http[s] 的图片地址
* @param url
* @returns {Promise<unknown>}
*/
function image2blob (url) {
return new Promise(resolve => {
// 如果是 data 开头的就使用 DataURI 的解析
if (url.indexOf('data:') === 0) {
return resolve(new ClipboardItem({ 'image/png': dataURItoBlob(url) }))
}
const img = new Image
const c = document.createElement('canvas')
const ctx = c.getContext('2d')
img.onload = function () {
c.width = this.naturalWidth
c.height = this.naturalHeight
ctx.drawImage(this, 0, 0)
c.toBlob(blob => resolve(new ClipboardItem({ 'image/png': blob })), 'image/png', 1)
}
img.crossOrigin = ''
img.src = url
})
}
/**
* 将 data: 开头的 dataURI base64 图片转为 blob
* @param dataURI
* @returns {Blob}
*/
function dataURItoBlob (dataURI) {
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0] // mime类型
var byteString = atob(dataURI.split(',')[1]) //base64 解码
var arrayBuffer = new ArrayBuffer(byteString.length) //创建缓冲数组
var intArray = new Uint8Array(arrayBuffer) //创建视图
for (var i = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i)
}
return new Blob([intArray], { type: mimeString })
}
/**
* 复制图片
* @param url
* @returns {Promise<unknown>}
*/
function copyImage (url) {
return new Promise((resolve, reject) => {
image2blob(url).then(data => {
navigator.clipboard.write([data]).then(resolve, reject)
})
})
}
window.onload = function () {
if (!document.hasFocus()) {
alert('必须窗口获得焦点')
return
}
copyImage(...).then(() => alert('复制成功'), (e) => alert(e))
}