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()
},
相关推荐
棋子一名4 小时前
跑马灯组件 Vue2/Vue3/uni-app/微信小程序
微信小程序·小程序·uni-app·vue·js
无衣 秦风5 小时前
vue3+hubuilderX开发微信小程序使用elliptic生成ECDH密钥对遇到的问题
微信小程序·小程序
游戏开发爱好者86 小时前
BShare HTTPS 集成与排查实战,从 SDK 接入到 iOS 真机调试(bshare https、签名、回调、抓包)
android·ios·小程序·https·uni-app·iphone·webview
2501_916008896 小时前
iOS 26 系统流畅度实战指南|流畅体验检测|滑动顺畅对比
android·macos·ios·小程序·uni-app·cocoa·iphone
流***陌7 小时前
陪诊就医小程序中健康档案的精细化管理设计方案
小程序
明天你好2677 小时前
如何做一个花店小程序,搭建一个小程序多少钱
微信小程序·小程序·模拟退火算法
2501_915106328 小时前
苹果软件加固与 iOS App 混淆完整指南,IPA 文件加密、无源码混淆与代码保护实战
android·ios·小程序·https·uni-app·iphone·webview
江城开朗的豌豆8 小时前
小程序登录不迷路:一篇文章搞定用户身份验证
前端·javascript·微信小程序
2501_915921438 小时前
iOS 26 崩溃日志解析,新版系统下崩溃获取与诊断策略
android·ios·小程序·uni-app·cocoa·iphone·策略模式
江城开朗的豌豆8 小时前
我的小程序登录优化记:从短信验证到“一键获取”手机号
前端·javascript·微信小程序