Thinking系列,旨在利用10分鐘的時間傳達一種可落地的編程思想。
水印是一種用于保護版權和識別內容的技術,通常用于圖像、視頻或文檔中。它可以是文本、圖像或兩者的組合,通常半透明或以某種方式嵌入到內容中,使其不易被移除或篡改。
今天主要闡述,如何在應用中添加動態水印「如下圖」。
靜態水印
① 將水印作為背景圖片嵌入到頁面或特定元素中。
.watermark-background {background-image: url('watermark.png');background-repeat: repeat;opacity: 0.5;
}
② 使用SVG(可縮放矢量圖形)可以創建高質量的圖像水印。SVG可以被嵌入到HTML中,并且可以很容易地通過CSS進行樣式化。
<svg width="100%" height="100%" style="position: fixed; top: 0; left: 0; z-index: -1;"><text x="50%" y="50%" fill="black" font-size="50" text-anchor="middle" opacity="0.05">版權所有</text>
</svg>
? 易于實現,且不會影響頁面的加載和渲染性能;
? 不存在層級(zIndex)問題,不會導致交互等問題;
? 容易被移除,且不能動態調整文案(在應用系統中,水印往往是登錄者信息)
動態水印
簡易 Demo
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');canvas.setAttribute('width', '200px')
canvas.setAttribute('height', '200px')ctx.translate(20, 20); // x、y移動20px
ctx.rotate((Math.PI / 180) * 45); // 旋轉45度ctx.font = 'normal 20px Arial';
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillText('李剛', 60, 0);
ctx.font = 'normal 14px Arial';
ctx.fillText('https://ligang.blog.csdn.net/', 0, 20);document.querySelector('body').style.backgroundImage = `url('${canvas.toDataURL()}')` // 以背景圖片形式追加
? 高度定制化:可以根據用戶行為或特定條件動態顯示或隱藏水印。
? 實現較復雜,對頁面性能可能有一定的影響(JavaScript實現)
如何防止被刪除
const observer = new MutationObserver((mutationList, observer) => {mutationList.forEach((mutation) => {// style 屬性被修改,重新追加if (mutation.type === 'attributes' && mutation.attributeName === 'style') {document.querySelector('body').style.backgroundImage = `url('${canvas.toDataURL()}')`}})
})// 接收body變化的通知
observer.observe(document.body, {childList: false, // 監聽 target 節點中發生的節點的新增與刪除(attributes: true, // 聽的 target 節點屬性值的變化subtree: false // 監聽以 target 為根節點的整個子樹(包括子樹中所有節點的屬性)
})
MutationObserver
提供了監視對 DOM 樹所做更改的能力。
🐾 上述簡單示意。實際使用時,需要水印寬高(注意像素比),以及水印之間的水平/垂直間距 等一些信息。具體可以參考 【WaterMark】