微信小程序截图分享 图片不清晰

微信截图分享 一般实现是通过微信小程序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

})

}

})

发现图片很模糊

后把高端替换为固定的

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值