Vue2實現(xiàn)全局水印效果的示例代碼
更新時間:2023年07月27日 11:46:27 作者:fruge
這篇文章主要為大家學習介紹了如何利用Vue2實現(xiàn)全局水印的效果,文中的示例代碼簡潔易懂,具有一定的借鑒價值,感興趣的小伙伴可以了解下
最近寫項目遇到一個需求,全局顯示水印,不管在哪個路由都要顯示。
想要實現(xiàn)的效果:

新建shuiyin.js文件
// 定義水印函數(shù)
const addWatermark = ({
container = document.body, // 水印添加到的容器,默認為 body
width = "200px", // 水印 canvas 的寬度
height = "100px", // 水印 canvas 的高度
textAlign = "center", // 水印文字的對齊方式
textBaseline = "middle", // 水印文字的基線
font = "16px Microsoft Yahei", // 水印文字的字體
fillStyle = "rgba(184, 184, 184, 0.6)", // 水印文字的填充樣式
content = "我是水印", // 水印文字的內容
rotate = -30, // 水印文字的旋轉角度
zIndex = 10000, // 水印的 z-index 值
}) => {
// 生成水印 canvas
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) / 1);
// 將 canvas 轉換為 base64 URL
const base64Url = canvas.toDataURL("image/png");
console.log(base64Url);
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: url('${base64Url}') left top repeat;
`;
watermarkDiv.setAttribute("style", styleStr);
watermarkDiv.classList.add("__wm");
// 則創(chuàng)建一個 div 并設置樣式和類名
if (!__wm) {
container.style.position = "relative";
container.insertBefore(watermarkDiv, container.firstChild);
}
// 監(jiān)聽容器變化,當容器發(fā)生變化時重新調用 addWatermark 函數(shù)
const { MutationObserver } = window;
if (MutationObserver) {
let mo = new MutationObserver(function () {
const __wm = document.querySelector(".__wm");
// 只在__wm元素變動才重新調用__canvasWM
if ((__wm && __wm.getAttribute("style") !== styleStr) || !__wm) {
// 避免一直觸發(fā)
mo.disconnect();
mo = new MutationObserver(() => {});
addWatermark({
container: document.getElementById("app"),
width: "200px",
height: "100px",
textAlign: "center",
textBaseline: "middle",
font: "16px Microsoft Yahei",
fillStyle: "rgba(184, 184, 184, 0.3 )",
content,
rotate: -30,
zIndex: 10000,
});
}
});
mo.observe(container, {
attributes: true,
subtree: true,
childList: true,
});
}
};
export default addWatermark;main.js中全局注冊
import addWatermark from "@/utils/shuiyin"; Vue.use(addWatermark);
到此這篇關于Vue2實現(xiàn)全局水印效果的示例代碼的文章就介紹到這了,更多相關Vue全局水印內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解vue數(shù)組遍歷方法forEach和map的原理解析和實際應用
這篇文章主要介紹了詳解vue數(shù)組遍歷方法forEach和map的原理解析和實際應用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
vue-admin-box第一步npm?install時報錯的處理
這篇文章主要介紹了vue-admin-box第一步npm?install時報錯的處理方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10

