前言: 很多项目都会涉及到一些隐私,或者避免泄露的一些敏感数据时。这时候给页面增加水印功能就会显得尤其重要了。思路: 1。首先是单独给某个页面或者图片增加水印功能,就需要能给指定容器去画水印。 2。还有一种,就是全局都是有水印。实现步骤: 1、核心方法,创建一个watermark。jsletwatermark{}letsetWatermark(text,sourceBody){letidMath。random()10000Math。random()10000Math。random()10000if(document。getElementById(id)!null){document。body。removeChild(document。getElementById(id))}letcandocument。createElement(canvas)can。width150can。height120letcanscan。getContext(2d)cans。rotate(20Math。PI180)cans。font15pxVedanacans。fillStylergba(0,0,0,。5)cans。textAlignleftcans。textBaselineMiddlecans。fillText(text,can。width20,can。height)letwaterpdocument。createElement(p)waterp。ididwaterp。style。pointerEventsnonewaterp。style。backgroundurl(can。toDataURL(imagepng))lefttoprepeatif(sourceBody){waterp。style。width100waterp。style。height100sourceBody。appendChild(waterp)}else{waterp。style。top3pxwaterp。style。left0pxwaterp。style。positionfixedwaterp。style。zIndex100000waterp。style。widthdocument。documentElement。clientWidthpxwaterp。style。heightdocument。documentElement。clientHeightpxdocument。body。appendChild(waterp)}returnid}该方法只允许调用一次param:text水印内容sourceBody水印添加在哪里,不传就是bodywatermark。set(text,sourceBody){letidsetWatermark(text,sourceBody)setInterval((){if(document。getElementById(id)null){idsetWatermark(text,sourceBody)}},2000)window。onresize(){setWatermark(text,sourceBody)}}exportdefaultwatermark 2、在main。js中全局配置水印importwatermarkfrom。utilswatermark。jsVue。prototype。watermarkwatermark 3、或者直接在页面引用importwatermarkfromlibwatermark。js;下面的放在mounted里面页面中使用指定容器watermark。set(水印文本,this。refs。mkp);某个p需要水印,需要提前给p设置ref属性watermark。set(水印文本);整个页面需要水印 4、如果觉得字体之间的距离太大了,改这个属性就行了can。width150can。height120