首页 » 前端 » Vue.js » 正文

Vue 开发中的项目添加水印用于提示运行版本

发布者:站点默认
2022/09/26 浏览数(287) 分类:Vue.js, 前端 Vue 开发中的项目添加水印用于提示运行版本已关闭评论
<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
export default {
  data() {
    return {
      waterMarkConfig: {
        width: 340,
        height: 240,
        content: '这里是水印内容,可以是 git commit id 或 process.env.NODE_ENV',
        font: '14px PingFang SC, sans-serif',
        color: 'rgba(0, 0, 0, 0.05)',
        rotate: -15, // 偏转角度(deg)
        x: 0,
        y: 100,
        position: 'absolute',
        top: 0,
        left: 0,
        zIndex: 1000,
        className: '#app:after',
      },
    };
  },
  methods: {
    createWaterMarkImage() {
      let self = this;
      const canvas = document.createElement('canvas');
      const text = self.waterMarkConfig.content;
      canvas.width = self.waterMarkConfig.width;
      canvas.height = self.waterMarkConfig.height;
      const ctx = canvas.getContext('2d');
      if (ctx) {
        ctx.shadowOffsetX = 2; // X轴阴影距离,负值表示往上,正值表示往下
        ctx.shadowOffsetY = 2; // Y轴阴影距离,负值表示往左,正值表示往右
        ctx.shadowBlur = 2; // 阴影的模糊程度
        ctx.font = self.waterMarkConfig.font;
        ctx.fillStyle = self.waterMarkConfig.color;
        ctx.rotate((self.waterMarkConfig.rotate * Math.PI) / 180);
        ctx.textAlign = 'left';
        ctx.fillText(text, self.waterMarkConfig.x, self.waterMarkConfig.y);
      }
      return canvas.toDataURL('image/png');
    },
    genWaterMark() {
      let self = this;
      const dataUri = self.createWaterMarkImage(self.waterMarkConfig);
      let styleEl = document.createElement('style');
      styleEl.innerHTML = `${self.waterMarkConfig.className} {
        content: '';
        display: block;
        width: 100%;
        height: 100%;
        pointer-events: none;
        background-repeat: repeat;
        background-attachment: fixed;
        background-image: url(${dataUri});
        background-size: ${self.waterMarkConfig.width}px ${self.waterMarkConfig.height}px;
        ${self.waterMarkConfig.position ? `position: ${self.waterMarkConfig.position}` : ''};
        ${self.waterMarkConfig.zIndex ? `z-index:${self.waterMarkConfig.zIndex}` : ''};
        ${self.waterMarkConfig.top || self.waterMarkConfig.top === 0 ? `top: ${self.waterMarkConfig.top}px;` : ''}
        ${self.waterMarkConfig.left || self.waterMarkConfig.left === 0 ? `left: ${self.waterMarkConfig.left}px;` : ''}
      }`;
      document.head.appendChild(styleEl);
    },
  },
  created() {
    let self = this;
    if (process.env.NODE_ENV !== 'production') {
      self.genWaterMark();
    }
  },
};
</script>

参考自:https://juejin.cn/post/6946139702684549157

点击返回顶部
  1. 留言
  2. 联系方式