前端水印生成

前端水印生成方法

/*
 * @Descripttion: 水印生成
 * @version: 0.0.1
 * @Author: guanxiaoxin
 * @Date: 2021-12-22 15:36:09
 * @LastEditors: guanxiaoxin
 * @LastEditTime: 2021-12-23 12:56:04
 * @FilePath: /guan_fun/background.js
 */

let isPc = () => {
  const userAgent = window.navigator.userAgent
  const userAgentsList = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone']
  let isPc = true
  userAgentsList.map(item => {
    if (userAgent.indexOf(item > 0)) {
      isPc = false
    }
  })
  return isPc
}

let canvasBackGround = (name = '背景') => {
  let container = document.body
  let canvas = document.createElement('canvas')
  canvas.height = window.innerHeight
  canvas.width = window.innerWidth
  let ctx = canvas.getContext('2d')
  ctx.font = '12px Arial'
  // 倾斜的宽高
  const Y = name.length * 1.414 / 2 * 40
  if (isPc()) {
    for (var x = 10; x < canvas.width; x = x + 300) {
      for (var y = 50; y < canvas.height; y = y + Y + 50) {
        ctx.beginPath()
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.font = '20px microsoft yahei'
        ctx.fillStyle = 'rgba(184, 184, 184, 0.4)'
        ctx.save()
        ctx.translate(x, y)
        ctx.rotate(-Math.PI / 4)
        ctx.fillText(name, 0, 25)
        ctx.restore()
      }
    }
  } else {
    for (var n = 10; n < canvas.width; n = n + 200) {
      for (var m = 50; m < canvas.height; m = m + Y + 20) {
        ctx.beginPath()
        ctx.textBaseline = 'middle'
        ctx.font = '18px microsoft yahei'
        ctx.fillStyle = 'rgba(184, 184, 184, 0.4)'
        ctx.save()
        ctx.translate(n, m)
        ctx.rotate(-Math.PI / 4)
        ctx.fillText(name, 0, 25)
        ctx.restore()
      }
    }
  }
  var srccc = canvas.toDataURL('image/png')
  // 加入页面
  const bodyMark = document.getElementById('bodyMark')
  if (bodyMark) {
    container.removeChild(bodyMark)
  }
  const box = document.createElement('div')
  box.setAttribute('id', 'bodyMark')
  const bodyMarkDiv = document.createElement('div')
  bodyMarkDiv.setAttribute('style', `position:fixed;top:0;left:0;width:100%;height:100%;z-index:1000;pointer-events:none;background-repeat:repeat;background-image:url('${srccc}')`)
  box.append(bodyMarkDiv)
  container.style.position = 'relative'
  container.insertBefore(box, container.firstChild)
}

效果图如下
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值