添加水印
项目中,需要对特定内容添加水印
代买实现为:
<template> <div> <div class="font-size">字体: <a class="large-font" @click="setFontSize(16)">大</a> <el-divider direction="vertical"></el-divider> <a class="med-font" @click="setFontSize(14)">中</a> <el-divider direction="vertical"></el-divider> <a class="small-font" @click="setFontSize(12)">小</a> </div> <div id="waterLaw" v-html="text" :style="{fontSize: sizeNum + 'px'}"></div> </div> </template> <script type="text/ecmascript-6"> /* eslint-disable */ import WarterMark from '../../utils/warterMark'; export default { props: [], name: '', mounted() { WarterMark.set('法律文本', 'waterLaw'); }, data () { return { sizeNum: 14, text: '' } }, methods: { setFontSize(num) { this.sizeNum = num; }, } }; </script> <style scoped> .font-size{ position: absolute; right: 4rem; } .large-font{ font-size: 16px; } .med-font{ font-size: 14px; } .small-font{ font-size: 12px; } p{ color: red !important; } </style>
WarterMark.set('法律文本', 'waterLaw')中,‘法律文本’是要显示的水印内容,waterLaw是需要展示水印的容器id。
在项目中使用是放在created函数中的。
this.$nextTick(() => { setTimeout(() => { WarterMark.set(this.waterContent, 'waterLaw'); }, 1000); });
其中:waterMark.js为:(可创建waterMark.js,直接复制后调用)
'use strict'; // 水印 let watermark = {}; let setWatermark = (str, domId) => { let id = '1.23452384164.123412415'; if (document.getElementById(id) !== null) { document.body.removeChild(document.getElementById(id)); } let can = document.createElement('canvas'); can.width = 320; can.height = 150; let cans = can.getContext('2d'); cans.rotate(-10 * Math.PI / 180); cans.font = '20px Vedana'; cans.fillStyle = 'rgba(200, 200, 200, 0.20)'; cans.textAlign = 'left'; cans.textBaseline = 'Middle'; cans.fillText(str, can.width / 3, can.height / 2); let div = document.createElement('div'); div.id = id; div.style.pointerEvents = 'none'; div.style.top = '10rem'; div.style.left = '10rem'; div.style.right = '15rem'; div.style.position = 'absolute'; div.style.zIndex = '100000'; // div.style.width = document.documentElement.clientWidth - 100 + 'px'; div.style.width = 'unset'; // div.style.height = document.documentElement.clientHeight - 100 + 'px'; div.style.height = '76%'; div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'; // console.log(document.getElementById(domId)); document.getElementById(domId).appendChild(div); return id; }; // 该方法只允许调用一次 watermark.set = (str, domId) => { // let id = setWatermark(str, domId); // setInterval(() => { // if (document.getElementById(id) === null) { // id = setWatermark(str, domId); // } // }, 500); setWatermark(str, domId); window.onresize = () => { setWatermark(str, domId); }; }; export default watermark;