vue2 系统增加水印

1 创建watermark.js

'use strict'
const watermark = {}
const setWatermark = (str, container) => {
    const id = '1.23452384164.123412415'
    if (container === undefined) {
        return
    }

    // 查看页面上有没有,如果有则删除
    if (document.getElementById(id) !== null) {
        const childelement = document.getElementById(id)
        childelement.parentNode.removeChild(childelement)
    }
    var containerWidth = container.offsetWidth // 获取父容器宽
    var containerHeight = container.offsetHeight // 获取父容器高
    container.style.position = 'relative' // 设置布局为相对布局
    // 创建canvas元素(先制作一块背景图)
    const can = document.createElement('canvas')
    can.width = 400 // 设置每一块的宽度
    can.height = 400 // 高度
    const cans = can.getContext('2d') // 获取canvas画布
    cans.rotate(-20 * Math.PI / 180) // 逆时针旋转π/9  
    cans.font = '20px Vedana' // 设置字体
    cans.fillStyle = 'rgba(0, 0, 0, 0.1)' // 设置字体的颜色
    cans.textAlign = 'left' // 文本对齐方式
    cans.textBaseline = 'Middle' // 文本基线
    cans.fillText(str, 0, 4 * can.height / 5) // 绘制文字
    // 创建一个div元素
    const div = document.createElement('div')
    div.id = id // 设置id
    div.style.pointerEvents = 'none' // 取消所有事件
    div.style.top = '0px'
    div.style.left = '0px'
    div.style.position = 'absolute'
    div.style.zIndex = '100000'
    div.style.width = containerWidth + 'px'
    div.style.height = containerHeight + 'px'
    div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
    container.appendChild(div) // 追加到页面
    return id
}
// 该方法只允许调用一次
watermark.set = (str, container) => {
    let id = setWatermark(str, container)
    setInterval(() => {
        if (document.getElementById(id) === null) {
            id = setWatermark(str, container)
        }
    }, 500)
    // 监听页面大小的变化
    window.onresize = () => {
        setWatermark(str, container)
    }
}
export default watermark

2 使用组件

<template>
  <div id="app" ref="containerS">
    <router-view />
  </div>
</template>
<script>
import Watermark from "@/plugins/waterMark.js";
export default {
  name: "App",
  data() {
    return {
      username: "John Doe", // 这里设置用户名作为水印内容
    };
  },
  watch: {
    $route(to, from) {
       this.$nextTick(function () {
        Watermark.set(this.username, this.$refs.containerS);
      });
    },
  },
  mounted() {
     this.$nextTick(function () {
      Watermark.set(this.username, this.$refs.containerS);
    });
  },
};
</script>>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容