javascript - 有没有办法使用没有库的纯 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 提供的链接:convert image into blob using javascript
这是我用于我的应用程序的解决方案(它只会将图像保存为 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)})
})
推荐阅读
- bluetooth-lowenergy - 主动 BLE 扫描 (BlueZ) - DBus 问题
- list - (wx)Maxima:将标量函数应用于列表的所有元素
- java - Spring Data JPA - 存储库返回不同的类型
- asp.net-core - 如何在 ASP.NET Core 中使用 Automapper 为以下类型的层次结构创建映射配置
- wix - 我想在没有原始 bundle.exe 的情况下通过 CMD 或 C# 代码卸载 BUNDLE
- angular - Angular 生产项目无法连接到后端
- lambda - 如何创建 Terraform,以便 AWS lambda 一旦添加到 S3 就可以对数据进行 pgp 加密
- javascript - 如何将 0 放在带小数的数字中?
- ios - 在 SWIFT 中访问 IOS 设备上的视频文件路径 URL
- javascript - 无限循环:BFS 获取嵌套对象的所有值(Javascript)