有没有任何方法可以在没有库的情况下用纯javascript将图像复制到剪贴板



我试过像这个网站一样使用document.execCommand('copy'(,但它不起作用(尽管console.log说它成功了,但没有任何东西被复制到我的剪贴板(。我还使用了navigator.clipboard API,但这对我的jpg图像不起作用,下面是它的代码:

navigator.clipboard.write(
[
new ClipboardItem({
'image/jpeg': new Blob( ['media/anime_0.jpg'],{type:'image/jpeg'} )
})
])
.then(e=>{console.log('Copied to clipboard')})
.catch(e=>{console.log(e)})

上述代码产生以下错误:

DOMException: Sanitized MIME type image/jpeg not supported on write.

有人知道我是否做错了什么,或者是否可以在不使用外部库的情况下将图像复制到剪贴板?

感谢Keith提供的链接:使用javascript 将图像转换为blob

这是我在应用程序中使用的解决方案(它只会将图像保存为png,因为jpeg/jpg文件不断给我DOMException错误。

const img = new Image
const c = document.createElement('canvas')
const ctx = c.getContext('2d')
function setCanvasImage(path,func){
img.onload = function(){
c.width = this.naturalWidth
c.height = this.naturalHeight
ctx.drawImage(this,0,0)
c.toBlob(blob=>{
func(blob)
},'image/png')
}
img.src = path
}
setCanvasImage('media/anime_0.jpg',(imgBlob)=>{
console.log('doing it!')
navigator.clipboard.write(
[
new ClipboardItem({'image/png': imgBlob})
]
)
.then(e=>{console.log('Image copied to clipboard')})
.catch(e=>{console.log(e)})
})

最新更新