微信小程序水印(换行,首行姓名,第二行电话)

可根据实际情况自己调整

onLoad() {
    this.getShuiYin()
},
async getShuiYin(){
    //text:传入的字符串(需要换行,则:'第一行\n第二行')
    //15:字号
    //#ddd:字体颜色
    let shuiyinImg = await util.textToImg(text, 15, '#ddd')
    this.setData({
      shuiyinBg: `url("${shuiyinImg}")`,
    })
}
const textToImg = function (text, fontsize, fontcolor) {
  return new Promise(resolve => {

    let buHeight = 0;
    if (fontsize <= 32) {
      buHeight = 99;
    } else if (fontsize > 32 && fontsize <= 60) {
      buHeight = 2;
    } else if (fontsize > 60 && fontsize <= 80) {
      buHeight = 4;
    } else if (fontsize > 80 && fontsize <= 100) {
      buHeight = 6;
    } else if (fontsize > 100) {
      buHeight = 10;
    }

    const lines = text.split('\n');

    let height = fontsize + buHeight + (lines.length - 1) * fontsize;
    wx.createSelectorQuery()
      .select('#canvas')
      .fields({
        node: true,
        size: true,
      })
      .exec(function (res) {
        console.log('res', res)

        const canvas = res[0].node
        canvas.padding = 30;
        const context = canvas.getContext('2d')

        context.clearRect(0, 0, canvas.width * 2, canvas.height);
        context.textAlign = "center"; // 设置文本居中对齐

        // 计算文本的宽度
        let textWidth = 0;
        lines.forEach(line => {
          const lineWidth = context.measureText(line).width;
          if (lineWidth > textWidth) {
            textWidth = lineWidth;
          }
        });

        canvas.width = textWidth + 80; // 根据文本的宽度调整画布宽度
        canvas.height = height;
        context.fillStyle = fontcolor;
        context.font = fontsize + "px Arial";
        context.textBaseline = 'middle';

        let y = fontsize / 2;
        lines.forEach(line => {
          const lineWidth = context.measureText(line).width;
          const x = canvas.width / 2 - lineWidth / 2; // 计算每行文本的x坐标位置
          context.fillText(line, x, y);
          y += fontsize;
        });

        console.log('canvas', canvas)
        var dataUrl = canvas.toDataURL('image/png');
        resolve(dataUrl)

      }.bind(this))
  })
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值