赞
踩
最近做了一个需求,给项目中所有的页面加上“当前登录人”的水印,找了一些资料,总结了两种可用方案,已在项目中测试有效。
第一种方案:watermark-dom 插件
1、安装命令npm install watermark-dom --save
2、在App.vue文件中
import watermark from 'watermark-dom' export default { name: 'App', watch: { //切换路由重新加载 $route (to, from) { const dataS = JSON.parse(sessionStorage.getItem("user")) let nameS = dataS.userName setTimeout(() => { watermark.init({ watermark_txt: nameS }) }, 1000) } }, mounted () { setTimeout(() => { //在缓存中获取当前登录人信息 const dataS = JSON.parse(sessionStorage.getItem("user")) let nameS = dataS.userName watermark.init({ watermark_txt: nameS }) }, 1000) } }
通过以上两步,就可以实现在所有页面中添加水印。
第二种方案:在网上找的手写Js
1、新建 waterMark.js 文件
'use strict' const watermark = {} const setWatermark = (str, container) => { const id = '1.23452384164.123412415' if (container === undefined) { return } // 查看页面上有没有,如果有则删除 if (document.getElementById(id) !== null) { const childelement = document.getElementById(id) childelement.parentNode.removeChild(childelement) } var containerWidth = container.offsetWidth // 获取父容器宽 var containerHeight = container.offsetHeight // 获取父容器高 container.style.position = 'relative' // 设置布局为相对布局 // 创建canvas元素(先制作一块背景图) const can = document.createElement('canvas') can.width = 260 // 设置每一块的宽度 can.height = 260 // 高度 const cans = can.getContext('2d') // 获取canvas画布 cans.rotate(-20 * Math.PI / 180) // 逆时针旋转π/9 cans.font = '24px Vedana' // 设置字体 cans.fillStyle = 'rgba(0, 0, 0, 0.1)' // 设置字体的颜色 cans.textAlign = 'left' // 文本对齐方式 cans.textBaseline = 'Middle' // 文本基线 cans.fillText(str, 0, 4 * can.height / 5) // 绘制文字 // 创建一个div元素 const div = document.createElement('div') div.id = id // 设置id div.style.pointerEvents = 'none' // 取消所有事件 div.style.top = '0px' div.style.left = '0px' div.style.position = 'absolute' div.style.zIndex = '100000' div.style.width = containerWidth + 'px' div.style.height = containerHeight + 'px' div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat' container.appendChild(div) // 追加到页面 return id } // 该方法只允许调用一次 watermark.set = (str, container) => { let id = setWatermark(str, container) setInterval(() => { if (document.getElementById(id) === null) { id = setWatermark(str, container) } }, 500) // 监听页面大小的变化 window.onresize = () => { setWatermark(str, container) } } export default watermark
2、 在App.vue文件中
<template> <div id="app" ref="containerS"> //ref是必须的 </div> </template> import Watermark from './utils/waterMark.js' watch:{ $route(to,from){ const dataS = JSON.parse(sessionStorage.getItem("user")) let nameS = dataS.userName this.$nextTick(function(){ Watermark.set(nameS, this.$refs.containerS); }) } }, mounted(){ const dataS = JSON.parse(sessionStorage.getItem("user")) let nameS = dataS.userName this.$nextTick(function(){ Watermark.set(nameS, this.$refs.containerS); }) },
注意:方式和第一种方案类似,但是需要在元素上加 ref
第二种方案,也可以达到效果。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。