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()
},
相关推荐
iOS阿玮1 小时前
AppStore教你一招免备案的骚操作!
uni-app·app·apple
racerun1 小时前
微信小程序如何实现再多个页面共享数据
微信小程序·小程序
XM-54582 小时前
2025微信小程序wxapkg解包全攻略
linux·运维·小程序
ModyQyW19 小时前
用 AI 驱动 wot-design-uni 开发小程序
前端·uni-app
HERR_QQ1 天前
【unify】unify的微信小程序开发学习 (to be continued)
学习·微信小程序·小程序
耶啵奶膘1 天前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
racerun1 天前
小程序导航设置更多内容的实现方法
小程序
说私域1 天前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的超级文化符号构建路径研究
人工智能·小程序·开源
mg6681 天前
微信小程序入门实例_____快速搭建一个快递查询小程序
微信小程序·小程序
程序员柳1 天前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui