项目中添加水印效果
vue 项目中添加水印效果
方法 1 通过 waterMark.js 实现
- 水印会随着页面滚动而滚动
-
waterMark.js
const watermark = {};
const setWatermark = (str, targetDom) => {
const id = "watermark";if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id));
}const can = document.createElement("canvas");
can.width = window.screen.width;
can.height = window.screen.height;const cans = can.getContext("2d");
cans.rotate((-20 * Math.PI) / 180);
cans.font = "20px serif";
cans.fillStyle = "rgba(180, 180, 180, 0.3)";
cans.textAlign = "left";
cans.textBaseline = "Middle";for (let i = -can.width / 10; i < can.width / 10; i++) {
for (let j = -can.height / 20; j < can.height / 20; j++) {
cans.fillText(str, i * 150, j * 80);
}
}
const div = document.createElement("div");
div.id = id;
div.style.pointerEvents = "none";
// div.style.position = "fixed"; // 水印固定
// div.style.top = targetDom.offsetTop + "px";
// div.style.left = targetDom.offsetLeft + "px";
div.style.top = "0px";
div.style.left = "0px";
div.style.position = "absolute";
div.style.zIndex = "100000";
div.style.width = targetDom.clientWidth + "px";
div.style.height = targetDom.clientHeight + "px";
div.style.background = "url(" + can.toDataURL("image/png") + ") left top repeat";
// document.body.appendChild(div); // 添加到boyd
targetDom.appendChild(div); // 添加到父级return id;
};// 如果水印存在 展示水印 如果不存在 创建之后展示
// targetDom 是水印要盖住的元素
watermark.set = (str, targetDom) => {
if (document.getElementById("watermark")) {
document.getElementById("watermark").style.display = "block";
} else {
let id = setWatermark(str, targetDom);
const timer = setInterval(() => {
if (document.getElementById(id) === null) {
id = setWatermark(str, targetDom);
} else {
clearInterval(timer);
}
}, 2000);
window.onresize = () => {
setWatermark(str, targetDom);
};
}
};
// 页面切换时展示水印 因为项目组件是keep-alive的 所以在beforeRouteEnter的时候调这个
watermark.show = () => {
if (document.getElementById("watermark")) {
document.getElementById("watermark").style.display = "block";
}
};
// beforeRouteLeave切换其他页面时可能需要隐藏水印
watermark.hide = () => {
document.getElementById("watermark").style.display = "none";
};
// 移除水印
watermark.remove = () => {
document.getElementById("watermark").remove();
};
export default watermark;
-
index.vue
<div @click="ontest">测试
1
2
3
4
5
方法 2 通过 watermark-dom 插件实现
- 效果图
![]()
npm 安装 watermark-dom
- 水印固定显示
- 安装
- npm install watermark-dom --S
-
引入
-
import watermark from "watermark-dom";
-
使用
const options = {
watermark_txt: "测试水印",
watermark_color: "gray",
watermark_fontsize: "24px",
};
watermark.load(options); -
移除
-
watermark.remove();
-
原文链接: https://blog.csdn.net/Shids_/article/details/140521115
-
detail.vue
11
21
31
41
51
61
71



浙公网安备 33010602011771号