代码实现
<template>
<div class="page">
<div id="to-img-dom">
<strong>我是图片标题</strong>
<p>
我是内容,我是内容,我是内容,我是内容,我是内容,我是内容,我是内容,我是内容,我是内容,我是内容,我是内容
</p>
<img class="icon" src="./../../assets/qr_code.png" alt="" />
</div>
<div>
<button style="margin: 12px; background-color: #ccc" @click="copyDivToImage">
转图片到剪贴板并下载
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import html2canvas from "html2canvas";
let copyDivToImage = () => {
// 获取要转换的元素
let element = document.getElementById("to-img-dom") as HTMLElement;
// 调用html2canvas
html2canvas(element).then((canvas) => {
canvas.toBlob(
async (blob) => {
// 复制文件到剪贴板
try {
await navigator.clipboard.write([
// eslint-disable-next-line no-undef
new ClipboardItem({
[blob!.type]: blob!,
}),
]);
console.log("图像已成功复制到剪贴板");
downloadClipboardImage();
} catch (err) {
console.error("无法复制图像到剪贴板", err);
}
},
"image/png", // 文件的格式
1 // 图像压缩质量 0-1
);
});
};
//把剪贴板图片下载到本地
let downloadClipboardImage = async () => {
try {
// 获取剪贴板中的数据
const data = await navigator.clipboard.read();
// 检查是否有图片数据
const imageData = data.find(
(item) => item.types.includes("image/png") || item.types.includes("image/jpeg")
);
if (imageData) {
const blob = await imageData.getType(imageData.types[0]);
// 创建一个临时的 URL
const url = URL.createObjectURL(blob);
// 创建一个隐藏的链接元素并触发点击事件来下载图片
const link = document.createElement("a");
link.href = url;
link.download = "clipboard-image.png";
link.click();
// 清理临时的 URL
URL.revokeObjectURL(url);
} else {
console.error("剪贴板中没有图片数据");
}
} catch (error) {
console.error("读取剪贴板数据失败:", error);
}
};
</script>
<style scoped lang="less">
.page {
display: flex;
align-content: center;
justify-content: center;
#to-img-dom {
padding: 12px;
width: 200px;
height: 300px;
background-image: url("./../../assets/bg.png");
background-size: 100% 100%;
border-radius: 8px;
.icon {
width: 100px;
height: 100px;
}
}
}
</style>