页面如何添加水印?

最近做vue项目的时候,需要要求要在页面中添加水印的效果,网上找了一些方法,具体操作如下:

(1)页面中添加一个文件比如 waterMark.ts, 代码如下: 

const watermark: any = {};

const setWatermark = (str: any) => {
    const id = '1.23452384164.123412415';

    if (document.getElementById(id) !== null) {
        document.body.removeChild(document.getElementById(id) as any);
    }

    const can = document.createElement('canvas');
    can.width = 400;
    can.height = 200;

    const cans: any = can.getContext('2d');
    cans.rotate((-30 * Math.PI) / 180); // 画布里面文字的旋转角度
    cans.font = '12px Microsoft JhengHei'; // 画布里面文字的字体
    cans.fillStyle = 'rgba(17, 17, 17, 0.3)'; // 画布里面文字的颜色
    cans.textAlign = 'center'; // 画布里面文字的水平位置
    cans.textBaseline = 'hanging'; // 画布里面文字的垂直位置
    cans.lineHeight = 400;
    cans.fillText(str, can.width / 3, can.height / 2); // 画布里面文字的间距比例

    const div = document.createElement('div');
    div.id = id;
    div.style.pointerEvents = 'none';
    div.style.overflow = 'hidden';
    div.style.opacity = '0.3';
    div.style.top = '64px';
    div.style.left = '0px';
    div.style.position = 'fixed';
    div.style.zIndex = '99999999';
    div.style.width = document.documentElement.clientWidth + 'px';
    div.style.height = document.documentElement.clientHeight + 'px';
    div.style.background = `url(${can.toDataURL('image/png')}) repeat`;
    document.body.appendChild(div);
    return id;
};

// 该方法只允许调用一次
watermark.set = (str: any) => {
    let id = setWatermark(str);
    setInterval(() => {
        if (document.getElementById(id) === null) {
            id = setWatermark(str);
        }
    }, 2000);
    window.onresize = () => {
        setWatermark(str);
    };
};

export default watermark;

(2)在要使用的地方引入并使用即可:

// Layout.vue

import watermark from './mark';

mounted() {
    watermark.set(`${this.tenantName} - ${this.displayName}`);
}

 

 

你可能感兴趣的:(vue,水印)