<template>
<div class="content">
<canvas :style="{width: canvasWidth + 'px', height: canvasHeight + 'px'}" type="2d" canvas-id="myCanvas1" id="myCanvas1"></canvas>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'canvas',
ctx: null,
canvas: null,
computed: {
...mapState(['userInfo'])
},
data () {
return {
// 比例是按750-1334这个尺寸等比缩放
canvasWidth: 187.5,
canvasHeight: 333.5
}
},
onReady () {
this.draw()
},
methods: {
async draw () {
const {avatarUrl, nickName} = this.userInfo
const qrCodeUrl = '图片地址'
const ctx = await this.initCanvas()
const ratio = this.canvasWidth / 750
// 按照总 width = 750 计算
const transform = n => n * ratio
// 基础背景
const background = await this.loadImage('图片地址')
ctx.drawImage(background, 0, 0, background.width, background.height, 0, 0, this.canvasWidth, this.canvasHeight)
// 头像
const avatar = await this.loadImage(avatarUrl)
ctx.save()
ctx.arc(transform(32 + 44), transform(32 + 44), transform(44), 0, 2 * Math.PI)
ctx.clip()
ctx.drawImage(avatar, 0, 0, avatar.width, avatar.height, transform(32), transform(32), transform(88), transform(88))
ctx.restore()
// 昵称 文案
ctx.font = `${transform(32)}px inherit bold`
ctx.fillStyle = '#222222'
ctx.fillText(nickName, transform(136), transform(32 + 32))
ctx.font = `${transform(24)}px inherit normal`
ctx.fillStyle = '#666666'
ctx.fillText('正在免费听每日热点资讯音频', transform(136), transform(80 + 24))
// 分享二维码
const qrcode = await this.loadImage(qrCodeUrl)
ctx.save()
ctx.drawImage(qrcode, 0, 0, qrcode.width, qrcode.height, transform(534), transform(1118), transform(168), transform(168))
ctx.restore()
},
initCanvas () {
if (this.canvas) {
return this.ctx
}
return new Promise((resolve, reject) => {
const query = this.createSelectorQuery()
query.select('#myCanvas1')
.fields({ node: true, size: true })
.exec((res) => {
if (!res || !res[0])
return reject(new Error('画布加载失败'))
const canvas = this.canvas = res[0].node
const ctx = this.ctx = canvas.getContext('2d')
const dpr = wx.getSystemInfoSync().pixelRatio
canvas.width = res[0].width * dpr
canvas.height = res[0].height * dpr
ctx.scale(dpr, dpr)
resolve(ctx)
})
})
},
loadImage (url) {
if (!this.canvas) return Promise.reject()
const canvas = this.canvas
const image = canvas.createImage()
image.src = url
return new Promise(resolve => (image.onload = () => resolve(image)))
},
}
}
</script>
<style scoped>
</style>
传入图片地址生成canvas分享海报
最新推荐文章于 2024-05-21 14:23:00 发布