Vue一招搞定前端水印开发
前言:
很多项目都会涉及到一些隐私,或者避免泄露的一些敏感数据时。这时候给页面增加水印功能就会显得尤其重要了。思路:
1.首先是单独给某个页面或者图片增加水印功能,就需要能给指定容器去画水印。
2.还有一种,就是全局都是有水印。实现步骤:
1、核心方法,创建一个watermark.jslet watermark = {} let setWatermark = (text, sourceBody) => { let id = Math.random()*10000+"-"+Math.random()*10000+"/"+Math.random()*10000 if (document.getElementById(id) !== null) { document.body.removeChild(document.getElementById(id)) } let can = document.createElement("canvas") can.width = 150 can.height = 120 let cans = can.getContext("2d") cans.rotate(-20 * Math.PI / 180) cans.font = "15px Vedana" cans.fillStyle = "rgba(0, 0, 0, .5)" cans.textAlign = "left" cans.textBaseline = "Middle" cans.fillText(text, can.width / 20, can.height ) let water_p = document.createElement("p") water_p.id = id water_p.style.pointerEvents = "none" water_p.style.background = "url(" + can.toDataURL("image/png") + ") left top repeat" if(sourceBody){ water_p.style.width = "100%" water_p.style.height = "100%" sourceBody.appendChild(water_p) }else{ water_p.style.top = "3px" water_p.style.left = "0px" water_p.style.position = "fixed" water_p.style.zIndex = "100000" water_p.style.width = document.documentElement.clientWidth + "px" water_p.style.height = document.documentElement.clientHeight + "px" document.body.appendChild(water_p) } return id } /** * 该方法只允许调用一次 * @param: * @text == 水印内容 * @sourceBody == 水印添加在哪里,不传就是body * */ watermark.set = (text, sourceBody) => { let id = setWatermark(text, sourceBody) setInterval(() => { if (document.getElementById(id) === null) { id = setWatermark(text, sourceBody) } }, 2000) window.onresize = () => { setWatermark(text, sourceBody) } } export default watermark
2、在main.js中全局配置// 水印 import watermark from "./utils/watermark.js" Vue.prototype.$watermark = watermark
3、或者直接在页面引用import watermark from "@/lib/watermark.js"; //下面的放在mounted里面 //页面中使用-指定容器 watermark.set("水印文本",this.$refs.mkp);//某个p需要水印, 需要提前给p设置ref属性 watermark.set("水印文本");//整个页面需要水印
4、如果觉得字体之间的距离太大了,改这个属性就行了can.width = 150 can.height = 120