需求
- 爲了防止截圖等安全問題,在web項目頁面中生成一個平鋪全屏的水印
- 要求水印內容爲用戶名,水印節點用戶不能通過開發者工具等刪除
效果
- 如上圖
- 在
body
節點下插入水印DOM節點,水印節點覆蓋在頁面最上層但不影響頁面正常操作 - 在通過js或者用戶通過開發者工具刪除或修改水印節點時自動復原
原理
- 通過
canvas
畫出節點需生成水印的文字生成base64
圖片 - 生成該水印背景圖的div節點插入到body下,通過js
MutationObserver
方法監聽節點變化,再自動重新生成
生成水印DOM節點
// 生成水印DOM節點
init () {
let canvas = document.createElement('canvas')
canvas.id = 'canvas'
canvas.width = '200' // 單個水印的寬高
canvas.height = '130'
this.maskDiv = document.createElement('div')
let ctx = canvas.getContext('2d')
ctx.font = 'normal 18px Microsoft Yahei' // 設置樣式
ctx.fillStyle = 'rgba(112, 113, 114, 0.1)' // 水印字體顏色
ctx.rotate(30 * Math.PI / 180) // 水印偏轉角度
ctx.fillText(this.inputText, 30, 20)
let src = canvas.toDataURL('image/png')
this.maskDiv.style.position = 'fixed'
this.maskDiv.style.zIndex = '9999'
this.maskDiv.id = '_waterMark'
this.maskDiv.style.top = '30px'
this.maskDiv.style.left = '0'
this.maskDiv.style.height = '100%'
this.maskDiv.style.width = '100%'
this.maskDiv.style.pointerEvents = 'none'
this.maskDiv.style.backgroundImage = 'URL(' + src + ')'
// 水印節點插到body下
document.body.appendChild(this.maskDiv)
},
監聽DOM更改
// 監聽更改,更改後執行callback回調函數,會得到一個相關信息的參數對象
Monitor () {
let body = document.getElementsByTagName('body')[0]
let options = {
childList: true,
attributes: true,
characterData: true,
subtree: true,
attributeOldValue: true,
characterDataOldValue: true
}
let observer = new MutationObserver(this.callback)
observer.observe(body, options) // 監聽body節點
},
使用
- 直接引入項目任何組件中使用即可
- 組件prop接收三個參數
props: {
// 顯示的水印文本
inputText: {
type: String,
default: 'waterMark水印'
},
// 是否允許通過js或開發者工具等途徑修改水印DOM節點(水印的id,attribute屬性,節點的刪除)
// true爲允許,默認不允許
inputAllowDele: {
type: Boolean,
default: false
},
// 是否在組件銷燬時去除水印節點(前提是允許用戶修改DOM,否則去除後會再次自動生成)
// true會,默認不會
inputDestroy: {
type: Boolean,
default: false
}
}
-
inputText(String):需要生成的水印文本,默認爲
'waterMark水印'
- inputAllowDele(Boolean):是否需要允許用戶刪除水印DOM節點,true爲允許,默認不允許
- inputDestroy(Boolean):是否在組件銷燬時去除水印節點,true會,默認不會,(只有在inputAllowDele爲ftrue時才能生效)
- 如果需要修改水印大小,文字,顏色等樣式,可直接進入組件中按註釋修改
小結
工作寫了個相關組件,複用率挺高就封裝了下,沒有經過嚴格測試,可當做參考使用
有需要的朋友歡迎下載源碼使用相關GitHub代碼