微信截图分享 一般实现是通过微信小程序canvas来实现,布局就靠固定画布宽度 来摆放元素,字体填充居中使用measureText,计算字体宽度,
有效调用时,需先初始化
onst ctx = wx.createCanvasContext('myCanvas')
this.setData({
ctx: ctx
})
const dpr = wx.getSystemInfoSync().pixelRatio
console.log(ctx, dpr)
// ctx.scale(dpr, dpr)
ctx.draw()
console.log(this.data.height_canvas)
this.data.ctx.drawImage('../../images/card_bg.png', 0, 0, 320, this.data.height_canvas)
this.data.ctx.setFontSize(30)
this.data.ctx.setFillStyle("#fb8e4b")
this.data.ctx.fillText("邀请卡", 115, 50)
this.data.ctx.setFontSize(12)
let metrics = this.data.ctx.measureText(this.data.teamInfo.shcool_name)
console.log(metrics, metrics.width, this.data.ctx.drawImage)
this.data.ctx.drawImage('../../images/location.png', (320 - metrics.width - 15) / 2, 80, 13, 15)
this.data.ctx.setFillStyle("#fb8e4b")
this.data.ctx.fillText(this.data.teamInfo.shcool_name, (320 - metrics.width - 15) / 2 + 15, 95)
this.data.ctx.setFontSize(12)
this.data.ctx.setFillStyle("#666666")
this.data.ctx.fillText("小组名称:" + this.data.teamInfo.group_name, 50, 130)
this.data.ctx.fillText("创建者:" + this.data.teamInfo.creator, 50, 160)
文字换行思路是:把字符串拆分为数组,计算宽度,超出指定宽度是换行在继续画
const temp = this.data.teamInfo.group_subject.split("")
console.log(temp)
let tes = "";
let i = 0;
temp.forEach((s, index) => {
tes += s;
if (this.data.ctx.measureText(tes).width > (220 - 60) && i < 2) {
this.data.ctx.fillText((i == 0 ? "小组主题:" : '') + tes, (i == 0 ? 50 : 50 + 60), 190 + i * 15)
tes = ""
i++
}
if (index == temp.length - 1 && tes != "") {
this.data.ctx.fillText((i == 0 ? "小组主题:" : '') + tes, (i == 0 ? 50 : 50 + 60), 190 + i * 15)
}
})
截图不清晰多半原因是因为宽高不固定导致的;
比如我遇到的刚开始我把高度设置为:原本是决定多设备适配高度 height_canvas: (wx.getSystemInfoSync().windowHeight - 130),宽度固定320px,canvas 与导出时一致,
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 320,
height: this.data.height_canvas,
destWidth: 320,
destHeight: this.data.height_canvas,
canvasId: 'myCanvas',
success: (res) => {
console.log(res.tempFilePath)
this.setData({
inviteImg: res.tempFilePath
})
}
})
发现图片很模糊
后把高端替换为固定的