vue实现为页面加水印

主要实现逻辑是先创建一个所需水印的canvas图片, 然后建一个div, 将canvas图片作为背景插入html

主要实现的方式是参考 https://www.jb51.net/article/221760.htm 感谢

1. 首先是创建一个js, 将水印的公共方法封装一下

let watermark = {};
let setWatermark = (text, sourceBody) => {
    let id = 'watermark_fjq_' + parseInt(Math.random() * 100000);
    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 = '#DCDCDC';//水印颜色
    cans.textAlign = 'left';
    cans.textBaseline = 'Middle';
    cans.fillText(text, can.width / 20, can.height);
    //设置插入div样式
    let water_div = document.createElement('div');
    water_div.id = id;
    water_div.style.pointerEvents = 'none';
    water_div.style.overflow = 'hidden';
    water_div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat';
    if (sourceBody) {
        sourceBody.style.position = 'relative';
        water_div.style.width = '100%';
        water_div.style.height = '100%';
        water_div.style.position = 'absolute';
        water_div.style.top = '0';
        water_div.style.left = '0';
        sourceBody.appendChild(water_div);
    } else {
        water_div.style.top = '3px';
        water_div.style.left = '0px';
        water_div.style.position = 'fixed';
        water_div.style.zIndex = '9999';
        water_div.style.width = document.documentElement.clientWidth + 'px';
        water_div.style.height = document.documentElement.clientHeight + 'px';
        document.body.appendChild(water_div);
    }
    return id;
}

/**
 *  该方法只允许调用一次
 *  @param:
 *  @text == 水印内容
 *  @sourceBody == 水印添加在哪里,不传就是body
 * */
watermark.set = (text, sourceBody) => {
    setTimeout(() => {
        setWatermark(text, sourceBody);
    }, 1000);//延迟加载
}

export default watermark;
View Code

2. 在需要的需要调用

import watermark from '@/lib/watermark.js';
watermark.set('水印文本',this.$refs.mkdiv);//某个div需要水印, 需要提前给div设置ref属性
watermark.set('水印文本');//整个页面需要水印

3. 查看效果

 

posted @ 2022-05-05 13:57  范斯  阅读(1785)  评论(0编辑  收藏  举报