react 页面统一添加可换行水印

1.组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const watermark = ({
  // 使用 ES6 的函数默认值方式设置参数的默认取值
  container = document.body,
  width = '250px',
  height = '160px',
  textAlign = 'left',
  textBaseline = 'bottom',
  font = '20px Microsoft Yahei',
  fillStyle = 'rgba(184, 184, 184, 0.4)',
  content = 'loading',
  content2 = 'time',
  rotate = '10',
  zIndex = 1000
} = {}, ...res) => {
const args = res
const canvas = document.createElement('canvas')
 
canvas.setAttribute('width', width)
canvas.setAttribute('height', height)
const ctx = canvas.getContext('2d')
 
ctx.textAlign = textAlign
ctx.textBaseline = textBaseline
ctx.font = font
ctx.fillStyle = fillStyle
ctx.rotate(Math.PI / 180 * rotate)
// ctx.fillText(content, 30, parseFloat(height) / 2)
ctx.fillText(content, 35, 15)
ctx.fillText(content2, 10, 40)
const base64Url = canvas.toDataURL()
const __wm = document.querySelector('.__wm')
const watermarkDiv = __wm || document.createElement('div')
const styleStr = `
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:${zIndex};
pointer-events:none;
background-repeat:repeat;
background-image:url('${base64Url}')`
 
watermarkDiv.setAttribute('style', styleStr)
watermarkDiv.classList.add('__wm')
 
if (!__wm) {
container.style.position = 'relative'
container.insertBefore(watermarkDiv, container.firstChild)
}
 
const MutationObserver = window.MutationObserver || window.WebKitMutationObserver
if (MutationObserver) {
let mo = new MutationObserver(function () {
const __wm = document.querySelector('.__wm')
console.log(__wm)
// 只在__wm元素变动才重新调用 __canvasWM
if ((__wm && __wm.getAttribute('style') !== styleStr) || !__wm) {
// 避免一直触发
mo.disconnect()
mo = null
watermark(JSON.parse(JSON.stringify(args)))
}
})
 
mo.observe(container, {
attributes: true,
subtree: true,
childList: true
})
}
 
}
 
export default watermark

2.入口文件引入

1
2
3
4
5
6
7
import watermark from './utils/watermark'
 
 
watermark({
  content: ‘水印内容’,
  container: document.querySelector('#root')
})

  

posted @   _心之所向便是光  阅读(624)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
点击右上角即可分享
微信分享提示