時(shí)間:2023-07-21 08:06:01 | 來源:網(wǎng)站運(yùn)營(yíng)
時(shí)間:2023-07-21 08:06:01 來源:網(wǎng)站運(yùn)營(yíng)
前端水印實(shí)現(xiàn)方案:本文作者:ELab.liujinbo,原文鏈接:前端水印實(shí)現(xiàn)方案 (juejin.cn)<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> #watermark-box { position: fixed; top: 0; bottom: 0; left: 0; right: 0; font-size: 24px; font-weight: 700; display: flex; flex-wrap: wrap; overflow: hidden; user-select: none; pointer-events: none; opacity: 0.1; z-index: 999; } .watermark { text-align: center; } </style> </head> <body> <div> <h2> 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- </h2> <br /> <h2> 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- </h2> <br /> <h2 onclick="alert(1)"> 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- 機(jī)密內(nèi)容- </h2> <br /> </div> <div id="watermark-box"> </div> <script> function doWaterMark(width, height, content) { let box = document.getElementById("watermark-box"); let boxWidth = box.clientWidth, boxHeight = box.clientHeight; for (let i = 0; i < Math.floor(boxHeight / height); i++) { for (let j = 0; j < Math.floor(boxWidth / width); j++) { let next = document.createElement("div") next.setAttribute("class", "watermark") next.style.width = width + 'px' next.style.height = height + 'px' next.innerText = content box.appendChild(next) } } } window.onload = doWaterMark(300, 100, '水印123') </script> </body> </html>
頁面效果是有了,但是這種方案需要要在js內(nèi)循環(huán)創(chuàng)建多個(gè)dom元素,既不優(yōu)雅也影響性能,于是考慮可不可以不生成這么多個(gè)元素。 <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="info" onclick="alert(1)" > 123 </div> <script> (function () { function __canvasWM({ container = document.body, width = '300px', height = '200px', textAlign = 'center', textBaseline = 'middle', font = "20px Microsoft Yahei", fillStyle = 'rgba(184, 184, 184, 0.6)', content = '水印', rotate = '45', zIndex = 10000 } = {}) { const args = arguments[0]; 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, parseFloat(width) / 2, parseFloat(height) / 2); const base64Url = canvas.toDataURL(); const __wm = document.querySelector('.__wm'); const watermarkDiv = __wm || document.createElement("div"); const styleStr = ` position:fixed; top:0; left:0; bottom:0; right: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.insertBefore(watermarkDiv, container.firstChild); } if (typeof module != 'undefined' && module.exports) { //CMD module.exports = __canvasWM; } else if (typeof define == 'function' && define.amd) { // AMD define(function () { return __canvasWM; }); } else { window.__canvasWM = __canvasWM; } })(); // 調(diào)用 __canvasWM({ content: '水印123' }); </script> </body></html>
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="info" onclick="alert(1)"> 123 </div> <script> (function () { function __canvasWM({ container = document.body, width = '300px', height = '200px', textAlign = 'center', textBaseline = 'middle', font = "20px Microsoft Yahei", fillStyle = 'rgba(184, 184, 184, 0.6)', content = '水印', rotate = '45', zIndex = 10000, opacity = 0.3 } = {}) { const args = arguments[0]; const svgStr = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${width}"> <text x="50%" y="50%" dy="12px" text-anchor="middle" stroke="#000000" stroke-width="1" stroke-opacity="${opacity}" fill="none" transform="rotate(-45, 120 120)" style="font-size: ${font};"> ${content} </text> </svg>`; const base64Url = `data:image/svg+xml;base64,${window.btoa(unescape(encodeURIComponent(svgStr)))}`; const __wm = document.querySelector('.__wm'); const watermarkDiv = __wm || document.createElement("div"); const styleStr = ` position:fixed; top:0; left:0; bottom:0; right: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); } if (typeof module != 'undefined' && module.exports) { //CMD module.exports = __canvasWM; } else if (typeof define == 'function' && define.amd) { // AMD define(function () { return __canvasWM; }); } else { window.__canvasWM = __canvasWM; } })(); // 調(diào)用 __canvasWM({ content: '水印123' }); </script> </body></html>
但是,以上三種方法存在一個(gè)共同的問題,由于是前端生成dom元素覆蓋到頁面上的,對(duì)于有些前端知識(shí)的人來說,可以在開發(fā)者工具中找到水印所在的元素,將元素整個(gè)刪掉,以達(dá)到刪除頁面上的水印的目的,針對(duì)這個(gè)問題,我想到了一個(gè)很笨的辦法:設(shè)置定時(shí)器,每隔幾秒檢驗(yàn)一次我們的水印元素還在不在,有沒有被修改,如果發(fā)生了變化則再執(zhí)行一次覆蓋水印的方法。網(wǎng)上看到了另一種解決方法:使用MutationObserverconst MutationObserver = window.MutationObserver || window.WebKitMutationObserver;if (MutationObserver) { let mo = new MutationObserver(function () { const __wm = document.querySelector('.__wm'); // 只在__wm元素變動(dòng)才重新調(diào)用 __canvasWM if ((__wm && __wm.getAttribute('style') !== styleStr) || !__wm) { // 避免一直觸發(fā) mo.disconnect(); mo = null; __canvasWM(JSON.parse(JSON.stringify(args))); } }); mo.observe(container, { attributes: true, subtree: true, childList: true })}}
整體代碼<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="info" onclick="alert(1)"> 123 </div> <script> (function () { function __canvasWM({ container = document.body, width = '300px', height = '200px', textAlign = 'center', textBaseline = 'middle', font = "20px Microsoft Yahei", fillStyle = 'rgba(184, 184, 184, 0.6)', content = '水印', rotate = '45', zIndex = 10000 } = {}) { const args = arguments[0]; 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, parseFloat(width) / 2, parseFloat(height) / 2); const base64Url = canvas.toDataURL(); const __wm = document.querySelector('.__wm'); const watermarkDiv = __wm || document.createElement("div"); const styleStr = ` position:fixed; top:0; left:0; bottom:0; right: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'); // 只在__wm元素變動(dòng)才重新調(diào)用 __canvasWM if ((__wm && __wm.getAttribute('style') !== styleStr) || !__wm) { // 避免一直觸發(fā) mo.disconnect(); mo = null; __canvasWM(JSON.parse(JSON.stringify(args))); } }); mo.observe(container, { attributes: true, subtree: true, childList: true }) } } if (typeof module != 'undefined' && module.exports) { //CMD module.exports = __canvasWM; } else if (typeof define == 'function' && define.amd) { // AMD define(function () { return __canvasWM; }); } else { window.__canvasWM = __canvasWM; } })(); // 調(diào)用 __canvasWM({ content: '水印123' }); </script> </body></html>
當(dāng)然,設(shè)置了MutationObserver之后也只是相對(duì)安全了一些,還是可以通過控制臺(tái)禁用js來跳過我們的監(jiān)聽,總體來說在單純的在前端頁面上加水印總是可以通過一些騷操作來跳過的,防君子不防小人,防外行不防內(nèi)行<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="info" onclick="alert(1)"> <img /> </div> <script> (function() { function __picWM({ url = '', textAlign = 'center', textBaseline = 'middle', font = "20px Microsoft Yahei", fillStyle = 'rgba(184, 184, 184, 0.8)', content = '水印', cb = null, textX = 100, textY = 30 } = {}) { const img = new Image(); img.src = url; img.crossOrigin = 'anonymous'; img.onload = function() { const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); ctx.textAlign = textAlign; ctx.textBaseline = textBaseline; ctx.font = font; ctx.fillStyle = fillStyle; ctx.fillText(content, img.width - textX, img.height - textY); const base64Url = canvas.toDataURL(); cb && cb(base64Url); } } if (typeof module != 'undefined' && module.exports) { //CMD module.exports = __picWM; } else if (typeof define == 'function' && define.amd) { // AMD define(function () { return __picWM; }); } else { window.__picWM = __picWM; } })(); // 調(diào)用 __picWM({ url: './a.png', content: '水印水印', cb: (base64Url) => { document.querySelector('img').src = base64Url }, }); </script> </body></html>
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> </head> <body> <canvas id="canvasText" width="256" height="256"></canvas> <canvas id="canvas" width="256" height="256"></canvas> <script> var ctx = document.getElementById('canvas').getContext('2d'); var ctxText = document.getElementById('canvasText').getContext('2d'); var textData; ctxText.font = '30px Microsoft Yahei'; ctxText.fillText('水印', 60, 130); textData = ctxText.getImageData(0, 0, ctxText.canvas.width, ctxText.canvas.height).data; var img = new Image(); var originalData; img.onload = function() { ctx.drawImage(img, 0, 0); // 獲取指定區(qū)域的canvas像素信息 originalData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); console.log(originalData); mergeData(textData,'G') console.log(document.getElementById('canvas').toDataURL()) }; img.src = './aa.jpeg'; var mergeData = function(newData, color){ var oData = originalData.data; var bit, offset; switch(color){ case 'R': bit = 0; offset = 3; break; case 'G': bit = 1; offset = 2; break; case 'B': bit = 2; offset = 1; break; } for(var i = 0; i < oData.length; i++){ if(i % 4 == bit){ // 只處理目標(biāo)通道 if(newData[i + offset] === 0 && (oData[i] % 2 === 1)){ // 沒有水印信息的像素,將其對(duì)應(yīng)通道的值設(shè)置為偶數(shù) if(oData[i] === 255){ oData[i]--; } else { oData[i]++; } } else if (newData[i + offset] !== 0 && (oData[i] % 2 === 0)){ // 有水印信息的像素,將其對(duì)應(yīng)通道的值設(shè)置為奇數(shù) if(oData[i] === 255){ oData[i]--; } else { oData[i]++; } } } } ctx.putImageData(originalData, 0, 0); } </script> </body></html>
顯示水印代碼實(shí)現(xiàn):<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> </head> <body> <canvas id="canvas" width="256" height="256"></canvas> <script> var ctx = document.getElementById('canvas').getContext('2d'); var img = new Image(); var originalData; img.onload = function() { ctx.drawImage(img, 0, 0); // 獲取指定區(qū)域的canvas像素信息 originalData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); console.log(originalData); processData(originalData) }; img.src = './a.jpg'; var processData = function(originalData){ var data = originalData.data; for(var i = 0; i < data.length; i++){ if(i % 4 == 1){ if(data[i] % 2 === 0){ data[i] = 0; } else { data[i] = 255; } } else if(i % 4 === 3){ // alpha通道不做處理 continue; } else { // 關(guān)閉其他分量,不關(guān)閉也不影響答案,甚至更美觀 o(^▽^)o data[i] = 0; } } // 將結(jié)果繪制到畫布 ctx.putImageData(originalData, 0, 0); } </script> </body></html>
這是一種比較簡(jiǎn)單的實(shí)現(xiàn)方式,有興趣想要了解更多的可以參看https://juejin.cn/post/6917934964202242061關(guān)鍵詞:方案,實(shí)現(xiàn),水印
客戶&案例
營(yíng)銷資訊
關(guān)于我們
客戶&案例
營(yíng)銷資訊
關(guān)于我們
微信公眾號(hào)
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。