1、首先设置html及引入静态文件
<div style="display: none;">
<img src="@/assets/img/personal/sy.png" class="man man-2" id="man-2" alt="">
<img src="@/assets/img/personal/bj1.png" id="bg1" alt="">
<img src="@/assets/img/personal/bj2.png" id="bg2" alt="">
<img src="@/assets/img/personal/voteImg@2x.png" alt="" id="man-1">
<img alt="" id="man-1">
<img alt="" id="qrCode">
</div>
2、canvas绘制方法
createdImageFun ():void {
const man1:any = document.getElementById('man-1')
const man2 = document.getElementById('man-2')
let canvasBg = document.getElementById('bg1')
if (this.schoolName === '' || !this.schoolName) {
canvasBg = document.getElementById('bg2')
}
const qrcodeImg:any = document.getElementById('qrCode')
const canvas:any = document.getElementById('myCanvas')
const ctx = canvas.getContext('2d')
let qrImage = new Image() // 二维码图片
canvas.width = 375 // bodyDOM.offsetWidth
canvas.height = 714
// 制作背景图
const patBg = ctx.createPattern(canvasBg, 'repeat')
ctx.rect(0, 0, 375, 714)
ctx.fillStyle = patBg
ctx.fill()
// 将man1,man2,man3,man4,sen1,btn加入画布
ctx.drawImage(man1, 0, 92, 375, 375)
ctx.drawImage(man2, 189, 386, 175, 70)
ctx.drawImage(qrcodeImg, 250, 595, 100, 100) // x ,y ,w, h
const schoolname = this.schoolName
const username = this.studentName
const userid = 'ID:' + this.studentCode
const memo = this.declaration
ctx.font = ' 16px MicrosoftYaHei-Bold'
ctx.fillStyle = '#FFFFFF'
ctx.fillText(schoolname, 127, 27, 80, 21)
ctx.fillStyle = '#4A4A4A'
ctx.fillText(username, 20, 494, 121, 21)
ctx.fillStyle = '#4A4A4A'
ctx.fillText(userid, 270, 494, 121, 21)
ctx.fillStyle = '#00ACF9'
ctx.fillText(memo, 20, 547, 324, 17)
const newImg = new Image()
newImg.src = canvas.toDataURL('image/png')
canvas.style = 'display: none';
(document.querySelector('.lpc-creatImg') as HTMLElement).appendChild(newImg)
this.canvasImgShow = true
this.dataLoading = false
}
使用方法:
this.$nextTick(() => {
var man1:any = document.getElementById('man-1')
man1.setAttribute('crossOrigin', 'anonymous') // 配置处理图片跨域问题
man1.src = this.userImage
var qrImage:any = document.getElementById('qrCode')
qrImage.setAttribute('crossOrigin', 'anonymous')
qrImage.src = this.qrImageHref
setTimeout(() => {
this.createdImageFun()
}, 1000)
})
问题:
从一开始的使用插件html2canvas绘制开始,遇到绘制一屏问题只能放弃;及QRCode生成二维码,domtoimage绘制在安卓及ios有兼容为题,最后选中还是直接用canvas绘制,遗留问题就是有点模糊;
3、其他问题
1⃣️对于line-height问题在安卓显示会有点偏上的问题,用padding撑开高度并配置line-height:normal;