uniapp 微信小程序 canvas 手写板文字重复倾斜水印

核心逻辑

先将坐标系中心点通过ctx.translate(canvasw / 2, canvash / 2) 平移到canvas 中心,再旋转设置水印

假如不 translate 直接旋转,则此时的旋转中心为左上角原点,此时旋转示意如图所示
当translate到中心点之后再旋转,此时则会变成这样

当 ctx.translate(x, y) 之后,实际上是将坐标系横移

此时ctx.fillText('水印文本', 0, 0) 的位置如图显示

我们循环从 -5 开始循环,此时得到的坐标点则为四个象限内均有

js 复制代码
for (var i = -5; i < 5; i++) {
 for (var j = -5; j < 5; j++) {
   const x = i * 140
   const y = j * 60
   this.canvasCtx.fillText('水印文本', x, y)
 }
}

此时,我们再进行旋转,ctx.rotate((-30 * Math.PI) / 180),注意,此时是 -30 度

其他:设置水印前需要存储一下状态 ctx.save(),水印设置完成后 ctx.restore()

水印完整代码

js 复制代码
// 设置水印文字
handleWaterMark: function (canvasw, canvash, text = '水印文本') {
  // 设置白色背景
  this.canvasCtx.fillStyle = '#fff'
  this.canvasCtx.fillRect(0, 0, canvasw, canvash)
  // 设置水印文字
  // 存储状态
  this.canvasCtx.save()
  this.canvasCtx.font = '16px sans-serif'
  this.canvasCtx.fillStyle = 'rgba(0, 0, 0, 0.2)'
  this.canvasCtx.translate(canvasw / 2, canvash / 2)
  this.canvasCtx.rotate((-30 * Math.PI) / 180)
  // 绘制水印
  for (var i = -5; i < 5; i++) {
    for (var j = -5; j < 5; j++) {
      const x = i * 140
      const y = j * 60
      this.canvasCtx.fillText(text, x, y)
    }
  }
  this.canvasCtx.draw(true)
  // 回退状态
  this.canvasCtx.restore()
},
相关推荐
小小王app小程序开发12 小时前
抽赏小程序特殊赏玩法开发全解析:技术实现+架构支撑+合规落地
小程序·架构
江南西肥肥12 小时前
从手绘图到小程序,我用AI花了2个小时完成
小程序·vibecoding·claudecode
Rysxt_16 小时前
Flutter与UniApp底层逻辑深度对比
flutter·uni-app
柠檬树^-^18 小时前
小程序定位
小程序
iOS阿玮18 小时前
死了么 - 官方正版惨遭下架,背后原因竟是ta!
uni-app·app·apple
计算机毕设指导618 小时前
基于微信小程序民宿预订管理系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
tjjucheng20 小时前
专业小程序定制开发公司推荐
大数据·小程序
莫非技术栈20 小时前
我模仿“死了吗“做了一个打卡签到的小程序
小程序
P7Dreamer20 小时前
微信小程序处理Range分片视频播放问题:前端调试全记录
前端·微信小程序