实现效果如下,这种水印用户无法从html删
具体代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#watermark-box{
width: 100%;
height: 90vh;
}
</style>
</head>
<body>
<div id="watermark-box"></div>
<script>
// text, fontSize, gap
function useWatermarkBg(props) {
const canvas = document.createElement('canvas')
const devicePixelRation = window.devicePixelRatio || 1
const fontSize = props.fontSize * devicePixelRation;
const font = fontSize + 'px serif'
const ctx = canvas.getContext('2d')
ctx.font = font
const {width} = ctx.measureText(props.text)
const canvasSize = Math.max(100, width) + props.gap * devicePixelRation
canvas.width = canvasSize
canvas.height = canvasSize
ctx.translate(canvas.width / 2, canvas.height / 2)
ctx.rotate((Math.PI / 180) * -45)
ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'
ctx.font = font
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(props.text, 0, 0)
return {
base64: canvas.toDataURL(),
size: canvasSize,
styleSize: canvasSize / devicePixelRation
}
}
let div;
// 生成水印
function createWaterMarkBox(){
const bg = useWatermarkBg({text: '江强华', fontSize: 20, gap: 10})
const {base64, styleSize} = bg
if (div) div.remove()
div = document.createElement('div')
div.style.backgroundImage = `url(${base64})`
div.style.backgroundSize = `${styleSize}px ${styleSize}px`
div.style.backgroundRepeat = 'repeat'
// div.style.width = '100%'
// div.style.height = '100%'
div.style.zIndex = 9999
div.style.position = 'absolute'
div.style.inset = 0
return div
}
// 放篡改水印
function listenChange() {
const ob = new MutationObserver(records => {
console.log('MutationObserver')
for (const record of records) {
// 检测是否被移出
for (const dom of record.removedNodes) {
if (dom === div){
console.log('删除了水印')
showWaterMark()
return
}
}
// 检测属性是否被修改
if (record.target === div) {
console.log('属性被修改')
showWaterMark()
return
}
}
})
ob.observe(document.getElementById('watermark-box'), {
childList: true,
attributes: true,
subtree: true
})
// ob.disconnect()
}
function showWaterMark () {
const waterMarkContent = createWaterMarkBox()
document.getElementById('watermark-box').appendChild(waterMarkContent)
}
listenChange()
showWaterMark()
</script>
</body>
</html>