复制JPG和PNG图片到剪切板是否成功实例页面
回到相关文章 »效果:
测试区
可以试试在这里粘贴(富文本输入框):
代码:
HTML代码:
<button id="button" type="primary" class="ui-button">复制JPG图片-左</button>
<button id="button2" type="primary" class="ui-button">复制PNG图片-右</button>
<div class="flex">
<figure>
<figcaption>jpg格式</figcaption>
<img id="image" src="./mybook.jpg">
</figure>
<figure>
<figcaption>png格式</figcaption>
<img id="image2" src="./mybook.png">
</figure>
</div>
JS代码:
const doCopyImg2Clipboard = async (image, success = () => {}, failure = () => {}) => {
if (!image || !image.src) {
return;
}
// 需要复制的图片的地址
const src = image.src;
// 请求该地址,返回图片的blob数据
const response = await fetch(src);
// 需要是blob数据格式
const blob = response.blob();
// 使用剪切板API进行复制
const data = [new ClipboardItem({
[blob.type || 'image/' + src.split('.').slice(-1)[0].replace('jpg', 'jpeg')]: blob
})];
navigator.clipboard.write(data).then(success, failure);
}
// 点击按钮进行复制
button.addEventListener('click', () => {
doCopyImg2Clipboard(image, function () {
new LightTip('复制成功', 'success');
}, function (err) {
new LightTip('复制失败:' + err, 'error');
});
});
button2.addEventListener('click', () => {
doCopyImg2Clipboard(image2, function () {
new LightTip('复制成功', 'success');
}, function (err) {
new LightTip('复制失败:' + err, 'error');
});
});