body,html {margin: 0;height: 100vh;width: 100vw;}
// 自定义文案const setting = {text: "水印文案", // 水印内容innerDate: true, // 在水印下方增加日期width: 110, // 水印宽度};// 自定义文字水印const watermark = (function () {return {build: function (arg) {// 获取页面宽度let maxWidth =Math.max(document.body.scrollWidth, window.screen.width) - 20;// 获取页面高度let maxHeight =Math.max(document.body.scrollHeight, document.body.clientHeight) +100;if (maxHeight === 0) {console.info("该页面无需水印");return;}const setting = {text: "水印 水印 水印", // 默认水印内容beginX: 50, // 默认起始x坐标endX: 0, // 默认结束x坐标beginY: 50, // 默认起始y坐标endY: 0, // 默认结束y坐标intervalX: 150, // 默认横向间隔宽度intervalY: 100, // 默认纵向间隔高度opacity: 0.3, // 字体透明度angle: 20, // 字体倾斜度fontsize: "15px", // 字体大小fontFamily: "微软雅黑", // 字体width: 100, // 水印(每个)宽度height: 80, // 水印(每个)高度innerDate: false, // 是否附带日期};// 默认变量与自定义变量结合if (arguments.length === 1 && typeof arguments[0] === "object") {const src = arguments[0] || {};for (const key in src) {if (!src.hasOwnProperty(key) || !src[key]) {continue;}for (const def in setting) {if (key === def) {setting[def] = src[key];}}}}// 计算列个数const cols = parseInt((setting.intervalX + maxWidth - setting.beginX - setting.endX) /(setting.width + setting.intervalX) +"");// 计算行个数const rows = parseInt((setting.intervalY + maxHeight - setting.beginY - setting.endY) /(setting.height + setting.intervalY) +"");// 水印内容附加日期if (setting.innerDate) {const date = new Date();setting.text = [setting.text,"<br>",date.getFullYear(),"年",date.getMonth() + 1,"月",date.getDate(),"日",].join("");}const fragment = document.createDocumentFragment();let x, y;for (let i = 0; i < rows; i++) {y = setting.beginY + (setting.intervalY + setting.height) * i;for (let j = 0; j < cols; j++) {x = setting.beginX + (setting.width + setting.intervalX) * j;const element = document.createElement("div");element.id = "watermark" + i + j;// 设置倾斜角element.style.MozTransform ="rotate(-" + setting.angle + "deg)";element.style.msTransform = "rotate(-" + setting.angle + "deg)";element.style.OTransform = "rotate(-" + setting.angle + "deg)";element.style.transform = "rotate(-" + setting.angle + "deg)";element.style.position = "absolute";element.style.left = x + "px";element.style.top = y + "px";element.style.overflow = "hidden";element.style.zIndex = "9999";element.style.pointerEvents = "none";element.style.opacity = setting.opacity;element.style.fontSize = setting.fontsize;element.style.fontFamily = setting.fontFamily;element.style.color = "#aaa";element.style.textAlign = "center";element.style.width = setting.width + "px";element.style.height = setting.height + "px";element.style.display = "block";element.innerHTML = setting.text;fragment.appendChild(element);}}document.body.appendChild(fragment);},};})();watermark.build(setting);
超链接:图片水印