vue中添加文字或图片水印
首先引用warterMark.js,内容如下
'use strict' var watermark = (className,str,type) => { let dom = document.getElementsByClassName(className) let canvas = document.createElement('canvas') let cxt = canvas.getContext('2d') let div = document.createElement('div') let imgScale = 0.6 canvas.width = 200 if(type == 'text'){ cxt.font = '16px Microsoft JhengHei' cxt.fillStyle = 'rgba(200, 200, 200, 0.3)' cxt.textAlign = 'left' cxt.textBaseline = 'Middle' cxt.fillText(str, 10, 50) cxt.clearRect(0, 0, canvas.width, canvas.height); div.style.background = 'url(' + canvas.toDataURL('image/png') + ') left top repeat' drawImage(div,dom) }else{ //创建新的图片对象 let img = new Image(); //指定图片的URL img.src = str; //浏览器加载图片完毕后再绘制图片 img.onload = function() { //cxt.drawImage(img,0,0); cxt.rotate(-20 * Math.PI / 180) let whScale = img.width / img.height cxt.clearRect(0, 0, canvas.width, canvas.height); cxt.drawImage(img, //规定要使用的图像、画布或视频。 0, 0, //开始剪切的 x 坐标位置。 img.width, img.height, //被剪切图像的高度。 0, 50,//在画布上放置图像的 x 、y坐标位置。 img.width * imgScale, img.height * imgScale //要使用的图像的宽度、高度 ) div.style.opacity = 0.3 div.style.background = 'url(' + canvas.toDataURL('image/png') + ') left top repeat' drawImage(div,dom) } } } var drawImage = function (div,dom) { div.style.pointerEvents = 'none' div.className = 'weterbox' div.style.top = 0 div.style.left = 0 div.style.position = 'absolute' div.style.zIndex = '100000' div.style.width = '100%' div.style.height = '100%' //console.log(dom) if( dom.length > 0){ for(let i = 0; i< dom.length;i++){ let child = dom[i].getElementsByClassName('weterbox') if(child.length > 0){ dom[i].removeChild(child[0]) } dom[i].appendChild(div.cloneNode(true)) // console.log(i,dom[i]) } } } export default watermark
在页面中调用,首先 import watermark from '@/libs/warterMark.js'
图片水印调用方法如下
watermark('需要添加水印的div元素的className','水印图片路径')
文字水印调用方法
watermark('需要添加水印的div元素的className','水印文字','text')
需要用到的样式
.viewWeb{ position: relative; }