vue 生成海报完整代码, (包括远程图片转base64、html2canvas 在IOS系统兼容的解决办法)

tech2026-08-20  2

最终效果:

1. html结构分为3部分:最终的海报图 + 内容布局 + 保存提示文字(可忽略)

<template> <section> <img :src="fullImg" v-if="fullImg" class="fullImg"> <div class="print" id="print" v-else> <img class="photo" :src="user.photo"> <div class="name">{{user.name}}</div> <div class="text1">自定义文字1</div> <div class="text2">自定义文字2</div> <div id="qrcode"><img id="qrImg" :src="user.code"></div> </div> <div class="end">长按海报保存到相册,分享邀请队友</div> </section> </template>

2. 逻辑实现思路

  海报大背景图放在了本地, 直接加给 #print

  头像 + 自定义文字 + 二维码 使用定位排好位置.

  获取到远程二维码图片url, 转为base64 然后赋值给qrImg

image2Base64(img, id) { let that = this var image = new Image() image.crossOrigin = 'Anonymous' // 注意这个属性一定要在src之前, 否则ios无法成功转base64 image.src = img image.onload = function(){ var canvas = document.createElement('canvas') canvas.width = image.width canvas.height = image.height var ctx = canvas.getContext('2d') ctx.drawImage(image, 0, 0, image.width, image.height) let base64 = canvas.toDataURL('image/png') document.getElementById(id).src = base64 setTimeout(function() { // 设置定时器, 保证二维码正确显示 再生成整个海报 that.toSave() }, 100) } },

3. https://github.com/FEA-Dven/html2Canvas 下载 html2canvas.js 放入本地文件夹.

// 引入 import html2canvas from "../../lib/html2canvas"; // 点击保存 toSave() { (window.html2canvas || html2canvas)(document.getElementById('print'), { useCORS: true //为了微信头像的跨域, 否则头像会空白 }).then((canvas) => { this.fullImg = canvas.toDataURL('image/png') }) },

这里需要特别注意一下!!!

(window.html2canvas || html2canvas)(document.getElementById('print'), {

如果写成下面这样:

var print = document.getElementById('print')

(window.html2canvas || html2canvas)(print, {

会报错 Uncaught TypeError: document.getElementById(...) is not a function 

或者写其他代码 也同样会报错, 比如: alert('xxx')  也会报错 Uncaught TypeError: alert(...) is not a function

好像是需要保证 (window.html2canvas || html2canvas) 首先被执行. 原因不明...

 

 

 

 

最新回复(0)