这是用vue框架生成的,使用其他的框架或者原生去写都是差不多,目前不处理兼容性问题,如果处理的话,添加个if条件查看用户设备是否支持canvas以及一些必要的属性吧~~~~
mounted() {
this.$axios({
url: '',
baseURL: '',
}).then(res => {
// 接口获取的数据
this.posterCanvas(res)
})
},
methods: {
// 创建img标签
imgLoadPromise(src) {
return new Promise((resolve, reject) => {
const img = new Image()
img.src = src
img.onload = function (e) {
resolve(img)
}
img.onerror = function (e) {
reject(img)
}
})
},
// 使用canvas生成图片
async posterCanvas(res) {
//将图片重新画入canvas中
let canvas = this.$refs.fswxpkposter // 获取canvas元素,根据框架自己方法获取,原生方法获取也行
let userInfo = res
let userAvatar = await this.imgLoadPromise(userInfo.user.avatar) // 发起者头像
let pkUserAvatar = await this.imgLoadPromise(userInfo.pkuser.avatar) // 挑战者头像
let width = 690
let height = 1325
let context = canvas.getContext('2d')
canvas.width = width
canvas.height = height
context.beginPath()
context.fillStyle = '#ffffff'
context.fillRect(0, 0, width, height)
context.fill()
context.closePath()
// 发起者头像--图片
context.drawImage(userAvatar, 110, 803, 144, 144)
// 发起者名字--zifu
context.font = '500 38px/1 \'PingFang SC\', \'STHeitiSC-Light\', \'Helvetica-Light\', arial, sans-serif, \'Droid Sans Fallback\''
context.fillStyle = '#170A28'
context.fillText(userInfo.user.nickname, 110, 995, 220)
// 发起者步数
context.font = '500 42px/1 \'PingFang SC\', \'STHeitiSC-Light\', \'Helvetica-Light\', arial, sans-serif, \'Droid Sans Fallback\''
context.fillStyle = '#170A28'
context.fillText(userInfo.user.total_step, 125, 750)
// 挑战者头像
context.drawImage(pkUserAvatar, 433, 803, 144, 144)
// 挑战者名字
context.font = '500 38px/1 \'PingFang SC\', \'STHeitiSC-Light\', \'Helvetica-Light\', arial, sans-serif, \'Droid Sans Fallback\''
context.fillStyle = '#170A28'
let psUserNameLeft = (width - 142 - userInfo.pkuser.nickname.length * 16)
context.fillText(userInfo.pkuser.nickname, psUserNameLeft, 995, 220)
// 挑战者步数
context.font = '500 42px/1 \'PingFang SC\', \'STHeitiSC-Light\', \'Helvetica-Light\', arial, sans-serif, \'Droid Sans Fallback\''
context.fillStyle = '#170A28'
let newPkStep = userInfo.pkuser.total_step.toString()
context.fillText(newPkStep, 432, 750, 200)
// 判断胜利img的left值在那里
let victoryLeft = userInfo.user.total_step >= userInfo.pkuser.total_step ? 60 : 370
// 生成海报
let replaceSrc = canvas.toDataURL('image/jpeg', 1)
this.posterImage = replaceSrc
},
}