前端實現(xiàn)添加水印功能的常見方式小結(jié)
一、簡介
簡單來說,前端水印就是在網(wǎng)頁或應(yīng)用程序的前端界面上添加的一種標(biāo)記,通常是文本、圖標(biāo)或圖案等形式。它就像給你的數(shù)字內(nèi)容貼上了一個獨(dú)特的 “標(biāo)簽”,用于標(biāo)識內(nèi)容的歸屬、防止未經(jīng)授權(quán)的使用和傳播。比如,一些在線圖片庫網(wǎng)站會在用戶瀏覽的圖片上添加透明的水印,顯示圖片的版權(quán)信息;視頻平臺也會在播放的視頻角落顯示平臺名稱或用戶標(biāo)識作為水印。
使用價值:
信息防盜:防止敏感信息截圖/錄屏傳播(金融/政務(wù)場景)
數(shù)據(jù)溯源:通過隱藏標(biāo)識追蹤泄露源頭
品牌標(biāo)識:增強(qiáng)產(chǎn)品品牌曝光(Saas類產(chǎn)品常見)
二、技術(shù)實現(xiàn)方案對比
1. DOM元素覆蓋方案
實現(xiàn)原理:通過絕對定位div覆蓋目標(biāo)區(qū)域
<style> .watermark { position: absolute; pointer-events: none; z-index: 9999; opacity: 0.3; transform: rotate(-15deg); } </style> <script> function createDOMWatermark(text) { const watermark = document.createElement('div'); watermark.className = 'watermark'; watermark.textContent = text; // 動態(tài)計算位置 const updatePosition = () => { const { clientWidth, clientHeight } = document.documentElement; watermark.style.width = `${clientWidth}px`; watermark.style.height = `${clientHeight}px`; }; window.addEventListener('resize', updatePosition); updatePosition(); document.body.appendChild(watermark); // 防刪除保護(hù) const observer = new MutationObserver((mutations) => { if (!document.contains(watermark)) { document.body.appendChild(watermark.cloneNode(true)); } }); observer.observe(document.body, { childList: true }); } </script>
- 優(yōu)勢:實現(xiàn)簡單、支持動態(tài)更新
- 缺陷:易通過開發(fā)者工具篡改、性能開銷大
2. Canvas動態(tài)繪制方案
實現(xiàn)原理:生成Base64圖片作為背景
function createWatermarkCanvas(text) { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); canvas.width = 300; canvas.height = 200; ctx.fillStyle = "rgba(100,100,100,0.3)"; ctx.font = "16px Arial"; ctx.rotate((-20 * Math.PI) / 180); ctx.fillText(text, 40, 180); const dataUrl = `url(${canvas.toDataURL("image/png")})`; document.body.style.backgroundImage = dataUrl; // 防止刪除元素 const observer = new MutationObserver((mutations) => { if ( mutations.some( (m) => m.target === document.body && m.attributeName === "style" && !m.target.style.backgroundImage ) ) { document.body.style.backgroundImage = dataUrl; } }); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["style"], }); } export default createWatermarkCanvas;
- 優(yōu)勢:防篡改等級中等、支持復(fù)雜圖形
- 缺陷:高清屏模糊、無法動態(tài)更新內(nèi)容
3. SVG矢量方案
function createSVGWatermark(text) { const svg = ` <svg width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <text x="50" y="180" transform="rotate(-20 50,180)" fill="rgba(100,100,100,0.3)" font-size="16"> ${text} </text> </svg>`; // 編碼為 base64 const btoa = (str) => window.btoa(unescape(encodeURIComponent(str))); const dataUrl = `url(data:image/svg+xml;base64,${btoa(svg)})`; document.body.style.backgroundImage = dataUrl; // 防止刪除元素 const observer = new MutationObserver((mutations) => { if ( mutations.some( (m) => m.target === document.body && m.attributeName === "style" && !m.target.style.backgroundImage ) ) { document.body.style.backgroundImage = dataUrl; } }); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["style"], }); } export default createSVGWatermark;
- 優(yōu)勢:矢量清晰、支持復(fù)雜圖形
- 缺陷:舊瀏覽器兼容性問題
4. 常用水印插件
1.watermark-dom
簡介:這是一個輕量級的 JavaScript 庫,專門用于為網(wǎng)頁添加水印。它使用簡單,可高度定制水印的樣式和內(nèi)容。
特點(diǎn)
- 支持自定義水印的文本內(nèi)容、字體、顏色、透明度、旋轉(zhuǎn)角度等。
- 可以通過 JavaScript 動態(tài)創(chuàng)建和修改水印。
- 可以應(yīng)用到指定的 DOM 元素或整個頁面。
使用示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Watermark Example</title> <script src="https://cdn.jsdelivr.net/npm/watermark-dom@3.0.4/dist/watermark.min.js"></script> </head> <body> <div id="content"> 這是頁面的主要內(nèi)容。 </div> <script> watermark({ watermark_txt: 'Confidential', watermark_x: 20, watermark_y: 20, watermark_rows: 20, watermark_cols: 20, watermark_x_space: 50, watermark_y_space: 50, watermark_font: '微軟雅黑', watermark_color: 'rgba(0, 0, 0, 0.15)', watermark_fontsize: '18px', watermark_alpha: 0.1, watermark_angle: 20 }); </script> </body> </html>
2.vue-watermark-directive
簡介:專為 Vue.js 框架設(shè)計的水印指令插件,方便在 Vue 項目中快速添加水印。
特點(diǎn)
- 以指令的形式使用,簡單易用,與 Vue 組件集成良好。
- 支持動態(tài)更新水印內(nèi)容和樣式。
- 可以應(yīng)用到單個組件或整個應(yīng)用。
使用示例
npm install vue-watermark-directive
<template> <div v-watermark="'Secret Information'"> 這是 Vue 組件的內(nèi)容。 </div> </template> <script> import VueWatermarkDirective from 'vue-watermark-directive'; export default { directives: { watermark: VueWatermarkDirective } }; </script>
3.react-watermark
簡介:用于 React 項目的水印組件,幫助開發(fā)者在 React 應(yīng)用中輕松添加水印。
特點(diǎn)
- 提供了封裝好的 React 組件,方便在 JSX 中使用。
- 支持自定義水印的各種屬性,如文本、顏色、大小等。
- 可以根據(jù)組件的狀態(tài)動態(tài)更新水印。
使用示例
npm install react-watermark
import React from 'react'; import ReactDOM from 'react-dom/client'; import Watermark from 'react-watermark'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Watermark content="Copyright" fontSize={16} color="rgba(0, 0, 0, 0.2)"> <div> 這是 React 應(yīng)用的內(nèi)容。 </div> </Watermark> );
4.jquery-watermark
簡介:基于 jQuery 庫的水印插件,適合已經(jīng)在項目中使用 jQuery 的開發(fā)者。
特點(diǎn)
- 利用 jQuery 的選擇器和方法,方便地為指定元素添加水印。
- 可以通過配置參數(shù)自定義水印的樣式和行為。
使用示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery Watermark Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/jquery-watermark@1.0.0/dist/jquery.watermark.min.js"></script> </head> <body> <div id="target"> 這是要添加水印的元素。 </div> <script> $(document).ready(function () { $('#target').watermark({ text: 'Private', font: 'Arial', color: 'rgba(0, 0, 0, 0.1)', fontSize: '20px' }); }); </script> </body> </html>
這些插件各有特點(diǎn),可以根據(jù)項目的技術(shù)棧和具體需求選擇合適的水印插件。
三、安全增強(qiáng)方案
1.DOM監(jiān)控系統(tǒng)
const securityObserver = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.removedNodes.length) { mutation.removedNodes.forEach(node => { if (node.classList.contains('watermark')) { document.body.appendChild(node.cloneNode(true)); } }); } }); }); securityObserver.observe(document.body, { attributes: true, childList: true, subtree: true });
2.多重防御機(jī)制
CSS防護(hù)層
.watermark-protect { user-select: none; -webkit-user-drag: none; pointer-events: none !important; }
事件攔截
document.addEventListener('contextmenu', e => e.preventDefault()); document.addEventListener('keydown', (e) => { if (e.ctrlKey && e.key === 's') e.preventDefault(); });
四、性能優(yōu)化策略
優(yōu)化手段 | 實施方式 | 效果提升 |
---|---|---|
離屏Canvas | 使用Worker預(yù)生成水印圖片 | 40%~60% |
CSS will-change | 對水印容器設(shè)置will-change: transform | 減少重繪 |
分層渲染 | 使用requestAnimationFrame批量更新 | 幀率穩(wěn)定 |
按需渲染 | IntersectionObserver控制可見區(qū)域渲染 | 內(nèi)存降低 |
// 離屏Canvas示例 const offscreenCanvas = new OffscreenCanvas(300, 200); const worker = new Worker('./watermark-worker.js'); worker.postMessage({ canvas: offscreenCanvas, text: 'Secure Mark' });
五、技術(shù)選型建議
- 普通業(yè)務(wù)場景:建議使用 DOM 方案,并結(jié)合 MutationObserver 進(jìn)行防護(hù)。
- 安全敏感場景:采用 Canvas 動態(tài)生成水印,并與用戶指紋綁定,增強(qiáng)安全性。
- 高清顯示需求:選擇 SVG 方案,并通過媒體查詢進(jìn)行適配,確保在不同設(shè)備上都能清晰顯示。
- 移動端場景:可以使用 CSS 重復(fù)背景,并配置 touch-action,提升用戶體驗。
一個完整的水印系統(tǒng)應(yīng)該包含版本管理、動態(tài)更新、埋點(diǎn)上報、異常監(jiān)控等功能模塊。同時,建議結(jié)合服務(wù)端實現(xiàn)水印信息的加密存儲,以保證水印數(shù)據(jù)的不可篡改性。
到此這篇關(guān)于前端實現(xiàn)添加水印功能的常見方式小結(jié)的文章就介紹到這了,更多相關(guān)前端添加水印內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序?qū)崙?zhàn)之上拉(分頁加載)效果(2)
這篇文章主要介紹了微信小程序?qū)崙?zhàn)之上拉加載、分頁加載效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04微信小程序非swiper組件實現(xiàn)的自定義偽3D輪播圖效果示例
這篇文章主要介紹了微信小程序非swiper組件實現(xiàn)的自定義偽3D輪播圖效果,涉及微信小程序事件響應(yīng)及元素屬性動態(tài)操作實現(xiàn)輪播圖效果相關(guān)技巧與注意事項,需要的朋友可以參考下2018-12-12