使用canvas添加全屏水印

793 阅读1分钟

使用canvas添加全屏水印

1.创建遮罩组件

<template>
  <div :class="$style.root" :style="{ backgroundImage: `url( ${url} )` }">
    <canvas id="canvas" style="display:none"></canvas>
  </div>
</template>

<script>
export default {
  data() {
    return {
      url: '', // 背景图片地址编码
      text: '管理员:009527' // 水印文本内容
    };
  },
  mounted() {
    this.draw(this.text);
  },
  methods: {
    draw(text) {
      // 创建画布
      let cvs = document.getElementById('canvas');
      // 画布尺寸
      cvs.width = 200;
      cvs.height = 180;
      // 上下文
      let ctx = cvs.getContext('2d');
      // 文字样式
      ctx.font = '25px 微软雅黑';
      // 文字旋转
      ctx.rotate((-45 * Math.PI) / 180);
      // 绘制文字(在指定的(x,y)位置填充指定的文本)
      // ctx.fillText(text, -110, 130);
      //设置画笔(绘制线条)操作的线条宽度,非必须;如果不写这句,那就是默认1
      ctx.lineWidth = 2;
      // 空心+实心
      ctx.strokeStyle = 'white';
      ctx.strokeText(text, -110, 130);
      ctx.fillStyle = 'black';
      ctx.fillText(text, -110, 130);
      // 生成base64图片编码
      let base64Url = cvs.toDataURL('image/png');
      // console.log(base64Url);
      this.url = base64Url;
    }
  }
};
</script>

<style lang="scss" module>
/* 遮罩尺寸为全屏 */
.root {
  width: 1920px;
  height: 1080px;
  opacity: 0.15;
}
</style>

2.在目标组件使用遮罩

<template>
  <div :class="$style.root">
    <!-- 目标组件内的子组件 -->
    <!-- ... -->
    <!-- 引入的全屏遮罩组件 -->
    <my-canvas :class="$style.mark"></my-canvas>
  </div>
</template>

<script>
// ...
import MyCanvas from './MyCanvas.vue';
export default {
  components: {
    // ...其它组件
    MyCanvas
  }
};
</script>

<style lang="scss" module>
.root {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  min-width: 1920px;
  background: #f4f6f8;
  overflow: hidden;
  .mark {
    /* 遮罩定位在目标组件之上 */
    position: absolute;
    top: -40px;
    left: 0;
    z-index: 999;
    /* 遮罩不遮挡下方元素的代码(关键) */
    -webkit-pointer-events: none;
    -moz-pointer-events: none;
    -ms-pointer-events: none;
    -o-pointer-events: none;
    pointer-events: none;
  }
}
</style>