全局水印的属性
// config/watermar.js
import { parseTime } from "@/utils/index";// 处理时间格式
export const content = `测试账号 | 图书管理 \n ${parseTime(+new Date())}`;
export default {
container: document.body,// 容器
zIndex: 1000,// 层级
font: "16px microsoft yahei",// 字体
color: "rgba(0,0,0,0.1)",// 颜色
content,// 文本内容
rotate: 30,// 旋转的角度
width: 300,// 宽度
height: 200,// 高度
repeat: true,// 是否重复
lh: 10,
};
自定义指令----全局水印,放在layout上
// waterMark.js
import config from "@/config/watermark";
export default {
bind(el, binding) {
let options;
console.log(binding);
if (typeof binding.value === "string") {
options = {
content: binding.value,
};
} else {
options = binding.value;
}
drawWatermark(Object.assign({ container: el }, config, options));
},
};
function drawWatermark({
container = document.body,
zIndex = 1000,
font = "16px microsoft yahei",
color = "rgba(0,0,0,0.1)",
content = "WATERMARK",
rotate = 30,
width = 200,
height = 200,
repeat = true,
lh = 10,
} = {}) {
if (!content) {
return;
}
const canvas = document.createElement("canvas");
canvas.setAttribute("width", `${width}px`);
canvas.setAttribute("height", `${height}px`);
const ctx = canvas.getContext("2d");
ctx.textAlign = "center";
ctx.textBaseline = "top";
ctx.font = font;
ctx.fillStyle = color;
ctx.rotate((Math.PI / 180) * rotate);
// console.log("ctxContent", content);
const strArr = content.split("\n");
const h = 18;
for (let j = 0; j < strArr.length; j++) {
const txt = strArr[j];
ctx.fillText(txt, width / 2, j * h + lh, width);
}
const base64Url = canvas.toDataURL();
const prevWatermarkDiv = container.firstChild;
let watermarkDiv;
if (prevWatermarkDiv && prevWatermarkDiv.id === "vue-watermark-directive") {
watermarkDiv = prevWatermarkDiv;
} else {
watermarkDiv = document.createElement("div");
watermarkDiv.id = "vue-watermark-directive";
}
watermarkDiv.setAttribute(
"style",
`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: ${zIndex};
pointer-events: none;
background-repeat: ${repeat ? "repeat" : "no-repeat"};
background-image: url('${base64Url}');
`
);
container.style.position = "relative";
if (!prevWatermarkDiv || prevWatermarkDiv.id !== "vue-watermark-directive") {
container.insertBefore(watermarkDiv, container.firstChild);
}
}