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 小时前
vue和微信小程序处理markdown格式数据
前端·vue.js·微信小程序
家里有只小肥猫7 小时前
uniApp小程序保存canvas图片
前端·小程序·uni-app
低代码布道师7 小时前
性格测评小程序10生成报告
低代码·小程序
小徐_23337 小时前
从空白到交互:用Trae快速搭建uni-app AI对话小程序页面
前端·uni-app·trae
科技小E8 小时前
EasyRTC:基于WebRTC与P2P技术,开启智能硬件音视频交互的全新时代
网络·网络协议·小程序·webrtc·p2p·智能硬件·视频监控
乔冠宇9 小时前
微信小程序中将图片截图为正方形(自动居中)
微信小程序·小程序·typescript·uniapp
播播资源10 小时前
ChatGPT付费创作系统V3.1.3独立版 WEB端+H5端+小程序端 (DeepSeek高级通道+推理输出格式)安装教程
前端·ai·chatgpt·ai作画·小程序·deepseek·deepseek-v3
貂蝉空大10 小时前
uni-app开发安卓和ios app 真机调试
android·ios·uni-app
程楠楠&M10 小时前
uni-app(位置1)
前端·javascript·uni-app·node.js
破z晓10 小时前
uniapp 整合openlayers 编辑图形文件并上传到服务器
前端·javascript·uni-app