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()
},
相关推荐
咖啡八杯5 小时前
微信小程序人脸认证1.0迁移2.0
后端·微信小程序
xshirleyl5 小时前
微信小程序开发week8-慕尚花坊项目
微信小程序·小程序
admin and root8 小时前
Claude+Trae大模型 配置Chrome MCP联动Yakit自动化渗透测试
微信小程序·渗透测试·自动化·攻防演练·ai安全·claude code·ai自动化渗透测试
织_网8 小时前
UniApp 快速集成个推推送(UniPush2.0)完整实战教程
uni-app
星星~笑笑9 小时前
vue 超简单 oss分片上传文件 大文件上传阿里云
前端·javascript·vue.js·uni-app
code_li20 小时前
小程序上线需要的资质证书汇总
小程序·上线·发布·资质
jingling5551 天前
uni-app农场地图——高德 JS API 实现全解析(天地图影像作为layers)
uni-app
hnxaoli1 天前
统信小程序(十三)循环键鼠操作程序
python·小程序
i查拉图斯特拉如是1 天前
使用workbuddy 30分钟搭建微信小程序
微信小程序·小程序
IceSugarJJ1 天前
Open-AutoGLM项目学习
语言模型·微信小程序·github