在网站开发中,为了防止用户截图或录屏暴露敏感信息,追踪用户来源,需要在网页中添加水印。
方式一:集成watermark组件
1、添加watermark-dom依赖
| npm install watermark-dom |
复制
2、在AppMain.vue文件引入水印模块
| import watermark from "watermark-dom"; |
| |
| export default { |
| name: "AppMain", |
| mounted() { |
| |
| |
| setInterval(() => { |
| const username = "我的水印"; |
| const serviceTime = parseTime(new Date()); |
| const option = { |
| watermark_txt: username + serviceTime, |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| }; |
| watermark.load(option); |
| }, 1000) |
| |
| window.addEventListener('resize', this.loadMark); |
| }, |
| computed: { |
| |
| }, |
| beforeDestory(){ |
| window.removeEventListener('resize', this.loadMark); |
| }, |
| }; |
复制
| |
| |
| watermark.load({ |
| watermark_txt: ' ' , |
| }) |
复制
3、访问页面,查看页面水印是否显示

方式二:使用canvas来画水印,防止水印信息被篡改
1、创建watermark.js
| |
| |
| |
| let setWatermark = (str1, str2) => { |
| let id = 'watermark_id'; |
| if (document.getElementById(id) !== null) { |
| document.body.removeChild(document.getElementById(id)); |
| } |
| let can = document.createElement('canvas'); |
| |
| can.width = 250; |
| can.height = 120; |
| let cans = can.getContext('2d'); |
| cans.rotate(-20 * Math.PI / 180); |
| cans.font = '15px Vedana'; |
| cans.fillStyle = '#000000'; |
| cans.textAlign = 'center'; |
| cans.textBaseline = 'middle'; |
| cans.fillText(str1, can.width / 2, can.height) |
| cans.fillText(str2, can.width / 2, can.height + 22); |
| |
| let div = document.createElement('div') |
| div.id = id; |
| div.style.pointerEvents = 'none'; |
| div.style.top = '40px'; |
| div.style.left = '0px'; |
| div.style.opacity = '0.15'; |
| div.style.position = 'fixed'; |
| div.style.zIndex = '100000'; |
| div.style.width = document.documentElement.clientWidth + 'px'; |
| div.style.height = document.documentElement.clientHeight + 'px'; |
| div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'; |
| document.body.appendChild(div); |
| return id; |
| } |
| |
| |
| export const setWaterMark = (str1, str2) => { |
| let id = setWatermark(str1, str2); |
| if (document.getElementById(id) === null) { |
| id = setWatermark(str1, str2); |
| } |
| } |
| |
| |
| export const removeWatermark = () => { |
| let id = 'watermark_id'; |
| if (document.getElementById(id) !== null) { |
| document.body.removeChild(document.getElementById(id)) |
| } |
| } |
复制
2、在AppMain.vue文件引入
| import { removeWatermark, setWaterMark } from '@/utils/watermark' |
| |
| export default { |
| name: 'AppMain', |
| mounted() { |
| |
| setInterval(() => { |
| setWaterMark("我的水印",parseTime(new Date())) |
| }, 1000) |
| }, |
| computed: { |
| |
| }, |
| beforeDestory(){ |
| removeWatermark(); |
| }, |
| } |
复制
3、访问页面,查看页面水印是否显示

