npm i qrcode.vue // 生成二维码
npm i html2canvas // 构建屏幕截图
<template>
<div class="page-share">
<div class="content">
<qrcode-vue id="ecode" value="https://fanyi.baidu.com/translate" level="H" />
<img class="bgImg" id="bg" src="@/assets/nwhome/futureCity.png" crossOrigin="anonymous" alt="">
<canvas id="myCanvas"></canvas>
<img :src="invitImg" ref="qrcode" alt="" crossOrigin="anonymous" style="width: 100%;height: 100%;">
</div>
<div class="save" @click="saveImg">保存图片</div>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref, getCurrentInstance} from 'vue'
import html2canvas from 'html2canvas'
import QrcodeVue from 'qrcode.vue'
const qrcode: any = ref(null)
const saveImg = () => {
html2canvas(qrcode.value,{
// useCORS: true,
// allowTaint: true,
// width: window.screen.availWidth,
// height: window.screen.availHeight,
// windowWidth: document.body.scrollWidth,
// windowHeight: document.body.scrollHeight,
// x:0,
// y:window.pageYOffset
}).then((canvas) => {
// let url = canvas.toDataURL('image/png');
let aLink = document.createElement("a");
// aLink.href = url;
aLink.href = invitImg.value;
aLink.download = new Date().toLocaleString() + '.png'
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
});
}
const invitImg: any = ref('')
const createImg = () => {
setTimeout(() => {
let img0 = document.getElementById('ecode')
let img1 = document.getElementById('bg');
let can: any = document.getElementById('myCanvas');
let ctx = can.getContext("2d");
let getPixelRatio = (context: any) => {
let backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
};
let ratio = getPixelRatio(ctx);
can.width = 170*ratio;
can.height = 287*ratio;
// 背景图片
ctx.drawImage(img1,0,0,170*ratio,287*ratio);
// 二维码
ctx.drawImage(img0,118.5*ratio,234.2*ratio,44*ratio,44*ratio);
invitImg.value = can.toDataURL("image/png");
localStorage.setItem('invitImg',invitImg.value)
},300)
}
onMounted(() => {
if( localStorage.getItem('invitImg')){
invitImg.value = localStorage.getItem('invitImg')
}else{
createImg()
}
})
</script>
<style lang="less" scoped>
.page-share{
.bgImg{
width: 100%;
height: 100%;
display: none;
}
canvas{
width: 340px;
height: 574px;
display: none;
}
}
</style>