前言:在进行H5开发的时候,遇到过这样的一个业务,用户登录,然后获取到用户的服务器名称、角色名称、邀请码,将它们弄在页面的一个卡片图片上,弄上去后生成一张可以长按保存的图片。
实现方法
用到了一个叫html2canvas的插件,利用插件将dom元素转成图片。
页面代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <template> <van-popup v-model:show="state.cardShow" class="pop" @closed="close" @opened="toImg" > <div class="card-wrap"> <div class="card-title">長按保存圖片</div> <div class="card" id="mycard" ref="mycard"> <img :src="htmlUrl" alt=""> <div class="sever-name" v-show="!hastoImg">{{ server }}</div> <div class="role-name" v-show="!hastoImg">{{ roleName }}</div> <div class="share-code" v-show="!hastoImg">{{ code }}</div> </div> </div> </van-popup> </template>
|
JavaScript实现方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| <script setup> import { ref, toRefs } from 'vue'; import userCounterStore from '@/stores/user'; import activityCounterStore from '@/stores/activity'; import html2canvas from "html2canvas" const { serverId, roleId, roleInfo, serverName, roleName } = toRefs(userCounterStore()); const { code } = toRefs(activityCounterStore());
const close = () =>{ htmlUrl.value = "./card2.png" hastoImg.value = false state.setCardShow(false) }
const htmlUrl = ref("./card2.png") const hastoImg = ref(false) const toImg = () =>{ let card = document.getElementById('mycard'); let scale = 3; html2canvas(card, { backgroundColor: null, useCORS: true, scale: scale, dpi: window.devicePixelRatio * 4, scrollY: -10, }).then((canvas) => { let url = canvas.toDataURL('image/png'); htmlUrl.value = url; console.log("htmlUrl",htmlUrl) hastoImg.value = true }).catch((e) => {}) }
</script>
|