有時候我們會用到將網頁上的東西轉換為圖片的需求,有一種插件就可以幫助我們來完成,現在我來介紹這個插件如何使用
1.安裝html2canvas
npm install --save html2canvas
2.導入
import html2canvas from "html2canvas";
3.html
<div ref="imageTofile">
<div>我是截取的內容</div>
</div>
<img :src="htmlUrl" v-show="isShow" />
4.轉成圖片的方法
toImage() {
html2canvas(this.$refs.imageTofile, {
backgroundColor: null,
}).then((canvas) => {
let url = canvas.toDataURL("image/png");
this.htmlUrl = url;
if (this.htmlUrl) {
this.isShow = true;
}
});
5.完整代碼(僅供參考)
<template>
<div>
<!-- 把需要生成截圖的元素放在一個元素容器里,設置一個ref -->
<div ref="imageTofile">
<!-- 這里放需要截圖的元素,自定義組件元素也可以 -->
<div>我是截取的內容</div>
<div>我是截取的內容</div>
<div>我是截取的內容</div>
<div>我是截取的內容</div>
<div>我是截取的內容</div>
</div>
<!-- 如果需要展示截取的圖片,給一個img標簽 -->
<img :src="htmlUrl" v-show="isShow" />
<button @click="toImage">截取</button>
</div>
</template>
<style scoped>
</style>
<script>
import html2canvas from "html2canvas";
export default {
data() {
return {
htmlUrl: "",
isShow: false,
};
},
methods: {
// 頁面元素轉圖片
toImage() {
// 第一個參數是需要生成截圖的元素,第二個是自己需要配置的參數,寬高等
html2canvas(this.$refs.imageTofile, {
backgroundColor: null,
}).then((canvas) => {
let url = canvas.toDataURL("image/png");
this.htmlUrl = url; // 把生成的base64位圖片上傳到服務器,生成在線圖片地址
if (this.htmlUrl) {
// 渲染完成之后讓圖片顯示,用v-show可以避免一些bug
this.isShow = true;
}
// this.sendUrl();
});
}, // 圖片上傳服務器
sendUrl() {
// 如果圖片需要formData格式,就自己組裝一下,主要看后台需要什么參數
// const formData = new FormData()
// formData.append('base64', this.company.fileUrl)
// formData.append('userId', 123)
// formData.append('pathName', 'pdf')
// ==================
// this.$ajax({
// url: apiPath.common.uploadBase,
// method: "post",
// data: this.htmlUrl,
// }).then((res) => {
// if (res.code && res.data) {
// }
// });
},
},
};
</script>
6.效果展示
7.參考
感謝https://www.cnblogs.com/shirliey/p/10647239.html博主給的思路