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()
},
相关推荐
蓝黑202013 小时前
从经纬度获取地理信息以及从地名获取经纬度
小程序
码云数智-园园19 小时前
和小鹅通一样的平台有哪些
微信小程序
吴声子夜歌1 天前
小程序——逻辑层
小程序
花木偶1 天前
小迪网安:APP攻防-Day1
安全·小程序
吴声子夜歌2 天前
小程序——生命周期函数和事件处理函数
服务器·前端·小程序
hnxaoli2 天前
win10程序(十六)通达信参数清洗器
开发语言·python·小程序·股票·炒股
码云数智-大飞3 天前
自助建站系统哪个好?快速建站哪个平台好
微信小程序
吴声子夜歌3 天前
小程序——项目结构
小程序
大黄说说3 天前
微信小程序制作平台有哪些?SaaS小程序搭建平台推荐
微信小程序
Lucky小黄人4 天前
微信小程序查看备案号
微信小程序·小程序