提交 | 用户 | 时间
|
820397
|
1 |
const domSymbol = Symbol('watermark-dom') |
H |
2 |
|
|
3 |
export function useWatermark(appendEl: HTMLElement | null = document.body) { |
|
4 |
let func: Fn = () => {} |
|
5 |
const id = domSymbol.toString() |
|
6 |
const clear = () => { |
|
7 |
const domId = document.getElementById(id) |
|
8 |
if (domId) { |
|
9 |
const el = appendEl |
|
10 |
el && el.removeChild(domId) |
|
11 |
} |
|
12 |
window.removeEventListener('resize', func) |
|
13 |
} |
|
14 |
const createWatermark = (str: string) => { |
|
15 |
clear() |
|
16 |
|
|
17 |
const can = document.createElement('canvas') |
|
18 |
can.width = 300 |
|
19 |
can.height = 240 |
|
20 |
|
|
21 |
const cans = can.getContext('2d') |
|
22 |
if (cans) { |
|
23 |
cans.rotate((-20 * Math.PI) / 120) |
|
24 |
cans.font = '15px Vedana' |
|
25 |
cans.fillStyle = 'rgba(0, 0, 0, 0.15)' |
|
26 |
cans.textAlign = 'left' |
|
27 |
cans.textBaseline = 'middle' |
|
28 |
cans.fillText(str, can.width / 20, can.height) |
|
29 |
} |
|
30 |
|
|
31 |
const div = document.createElement('div') |
|
32 |
div.id = id |
|
33 |
div.style.pointerEvents = 'none' |
|
34 |
div.style.top = '0px' |
|
35 |
div.style.left = '0px' |
|
36 |
div.style.position = 'absolute' |
|
37 |
div.style.zIndex = '100000000' |
|
38 |
div.style.width = document.documentElement.clientWidth + 'px' |
|
39 |
div.style.height = document.documentElement.clientHeight + 'px' |
|
40 |
div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat' |
|
41 |
const el = appendEl |
|
42 |
el && el.appendChild(div) |
|
43 |
return id |
|
44 |
} |
|
45 |
|
|
46 |
function setWatermark(str: string) { |
|
47 |
createWatermark(str) |
|
48 |
func = () => { |
|
49 |
createWatermark(str) |
|
50 |
} |
|
51 |
window.addEventListener('resize', func) |
|
52 |
} |
|
53 |
|
|
54 |
return { setWatermark, clear } |
|
55 |
} |